﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities;
using ARR.DataModel.Repositories;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
using ARR.Entities.Gateways;
using ARR.Model.Repositories;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Telerik.Web.UI;
using Telerik.Charting;
using ARR.Shared;
using System.Configuration;
using System.ServiceModel;
using System.Globalization;
using iTextSharp.text.html.simpleparser;
using ARR.Services.Domain.Reports;
using System.Linq.Expressions;

namespace ARR.Services.Domain
{
    public static class ReportsDomain
    {
        public static List<SalesCategoryComparisonByDateRow> GetSalesCategoryComparisonByDate(int rangeReviewId, int categoryId)
        {
            return ReportsRepository.GetSalesCategoryComparisonByDate(rangeReviewId, categoryId, 1).ToList();
            //return rows.ConvertAll<SalesCategoryComparisonByDateRow>(c => new SalesCategoryComparisonPareto(c));
        }

        public static List<SalesCategoryComparisonBySpace> GetSalesCategoryComparisonBySpace(int rangeReviewId, int categoryId)
        {
            var rows = ReportsRepository.GetSalesCategoryComparisonBySpace(rangeReviewId, categoryId, false, 1);
            return rows.ConvertAll<SalesCategoryComparisonBySpace>(row => new SalesCategoryComparisonBySpace(row));
        }

        public static IList<ImporterResult> ValidateCategoryReportGeneration(RangeReview rangeReview, int categoryId)
        {
            List<ImporterResult> importerResults = new List<ImporterResult>();

            var missings = RangeReviewSetupRepository.RangeReviewSetup_CheckMissings(rangeReview.Id, categoryId, true);
            int errorCount = 0;

            var setups = RangeReviewDomain.GetRangeReviewSetups(rangeReview.Id, categoryId);

            //TODO: faltaria incluir los RangeReviewSetupAttributes 
            foreach (var setup in setups)
            {
                if (setup.Category.Level == 2) //Si es una categoria agrupo los resultados para mostrar los totales
                {
                    missings = (from m in missings
                                where m.ParentId == setup.CategoryId
                                group m by new { m.ParentId, m.Attribute, m.TypeId, m.CategoryName } into g
                                select new ARR.Entities.Gateways.RangeReviewSetupMissingsRow { CategoryName = g.Key.CategoryName, TypeId = g.Key.TypeId, Attribute = g.Key.Attribute, ParentId = g.Key.ParentId, Missings = g.Sum(x => x.Missings) }).ToList();
                }
                else
                {
                    missings = (from m in missings
                                where m.CategoryId == setup.CategoryId
                                select m).ToList();
                }

                foreach (var missing in missings)
                {
                    bool hasError = false;
                    if (setup.Brand && missing.Attribute == "Brand")
                    {
                        hasError = true;
                    }

                    if (setup.Manufacturer && missing.Attribute == "Manufacturer")
                    {
                        hasError = true;
                    }

                    if (setup.Attribute1 && missing.Attribute == "Attribute1")
                    {
                        hasError = true;
                    }

                    if (setup.Attribute2 && missing.Attribute == "Attribute2")
                    {
                        hasError = true;
                    }

                    if (setup.Attribute3 && missing.Attribute == "Attribute3")
                    {
                        hasError = true;
                    }

                    if (setup.Attribute4 && missing.Attribute == "Attribute4")
                    {
                        hasError = true;
                    }

                    if (setup.Attribute5 && missing.Attribute == "Attribute5")
                    {
                        hasError = true;
                    }

                    if (hasError || missing.TypeId == 2)
                    {
                        errorCount++;
                        ImporterResult result = new ImporterResult
                        {
                            Category = ResultCategory.Validation,
                            ErrorType = ErrorType.Warning,
                            Param1 = missing.CategoryName,
                            Param2 = missing.SubCategoryName,
                            Param3 = missing.Attribute,
                            Param4 = missing.Missings.ToString(),
                            Id = errorCount
                        };

                        if (missing.TypeId == 1)
                        {
                            result.Description = missing.Missings.ToString() + " " + missing.Attribute + " missings";
                            result.Workaround = Workaround.MissingSegmentation;
                        }
                        else if (missing.TypeId == 2)
                        {
                            result.Description = "Missing " + missing.Attribute;
                            result.Workaround = Workaround.MissingSales;
                        }

                        importerResults.Add(result);
                    }
                }
            }

            return importerResults;
        }

        public static byte[] GetSalesCategoryComparison(int rangeReviewId, int categoryId)
        {
            //return QuickTest(rangeReviewId, categoryId);


            RangeReview rangeReview = RangeReviewDomain.GetById(rangeReviewId, true);
            Category category = CategoriesDomain.GetById(categoryId);

            //Culture
            var country = CountriesRepository.Select(x => x.Id == rangeReview.CountryId).FirstOrDefault();
            if (country.Code == "US" || country.Code == "CA")
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            }

            var targetCurrency = CurrenciesRepository.Select(x => x.Id == rangeReview.TargetCurrencyId).SingleOrDefault();

            NumberFormatInfo numberFormatInfo = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
            string currencySymbol = targetCurrency.CurrencySymbol;
            numberFormatInfo.CurrencySymbol = currencySymbol;
            numberFormatInfo.CurrencyPositivePattern = 2;
            numberFormatInfo.CurrencyNegativePattern = 12;
            if (numberFormatInfo.CurrencyDecimalSeparator == ",")
            {
                numberFormatInfo.CurrencyGroupSeparator = ".";
            }
            else
            {
                numberFormatInfo.CurrencyGroupSeparator = ",";
            }
            System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat = numberFormatInfo;

            var rows = ReportsRepository.GetSalesCategoryComparison(rangeReviewId, categoryId, null, null).ToList();
            List<SalesCategoryComparison> sales = rows.ConvertAll<SalesCategoryComparison>(c => new SalesCategoryComparison(c));

            //Construyo el Pareto
            var paretoRowsWithPY = ReportsRepository.GetSalesCategoryComparisonPareto(rangeReviewId, categoryId, true, 0, 1).Where(x => !x.IsDeletedPerformance).ToList();
            List<SalesCategoryComparisonPareto> paretoItemsWithPY = paretoRowsWithPY.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

            var paretoRows = paretoRowsWithPY.Where(x => !x.IsPriorYear).ToList();
            List<SalesCategoryComparisonPareto> paretoItems = paretoRows.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

            BaseFont Calibri = ReportsHelper.GetCalibriOrDefault();

            Font font = new Font(Calibri, 9, Font.NORMAL, BaseColor.BLACK);
            Font fontRed = new Font(Calibri, 9, Font.NORMAL, BaseColor.RED);
            PdfPCell emptyTableCell = new PdfPCell(new Phrase(" "));
            emptyTableCell.Border = PdfPCell.NO_BORDER;
            if (sales != null && sales.Count() > 0)
            {
                #region Report Configuration
                SalesCategoryComparison sale = sales.Where(x => !x.IsPriorYear).First();
                SalesCategoryComparison salePY = sales.Where(x => x.IsPriorYear).FirstOrDefault();

                //Traigo los datos de RangeReviewBenchmarks, hasta 3 columnas para la primer pagina.
                SalesCategoryComparison saleColumn1 = null;
                SalesCategoryComparison saleColumn2 = null;
                SalesCategoryComparison saleColumn3 = null;
                var benchmarks = RangeReviewBenchmarksRepository.Select(x => x.RangeReviewSourceId == rangeReviewId).OrderBy(x => x.ColumnNumber).ToList();
                var setup = RangeReviewSetupRepository.Select(x => x.RangeReviewId == rangeReviewId && x.CategoryId == categoryId).FirstOrDefault();
                if (setup == null)
                {
                    throw new NotImplementedException("Falta definir la configuración del Range Review para esta categoría");
                }
                int countColumns = 0;
                foreach (var benchmark in benchmarks)
                {
                    List<SalesCategoryComparisonRow> columnRows;
                    if (benchmark.HistoryGroupId.HasValue)
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparisonHistoryBenchmark(rangeReviewId, categoryId, benchmark.HistoryGroupId.Value, false, false).ToList();
                    }
                    else
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparison(rangeReviewId, categoryId, benchmark.StoreId, benchmark.StoreGroupId).ToList();
                    }

                    if (columnRows.Count > 0)
                    {
                        List<SalesCategoryComparison> salesColumn = columnRows.ConvertAll<SalesCategoryComparison>(c => new SalesCategoryComparison(c));
                        switch (countColumns)
                        {
                            case 0:
                                saleColumn1 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                            case 1:
                                saleColumn2 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                            case 2:
                                saleColumn3 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                        }
                        countColumns++;
                    }
                }

                //string fileName = @"C:\Test.pdf";
                Document document = new Document(PageSize.LETTER.Rotate(), 0, 0, 0, 0);

                List<GeneralComment> generalComments = GeneralCommentsRepository.Select(x => x.RangeReviewId == rangeReview.Id && x.ReportType == ReportType.CategoryReport.ToString())
                                                                                .Where(x => x.CategoryId == categoryId || !x.CategoryId.HasValue)
                                                                                .ToList()
                                                                                .ConvertAll<GeneralComment>(row => new GeneralComment(row));

                // step 2
                MemoryStream stream = new MemoryStream();

                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new PageEvent();
                ((PageEvent)writer.PageEvent).GeneralComments = generalComments;

                // step 3
                document.Open();

                System.Drawing.Color[] barColors = new System.Drawing.Color[]
                {
                       System.Drawing.Color.FromArgb(70, 119, 172),
                       System.Drawing.Color.FromArgb(173, 71, 68),
                       System.Drawing.Color.FromArgb(141, 169, 78),
                       System.Drawing.Color.FromArgb(115, 90, 143),
                       System.Drawing.Color.FromArgb(66, 154, 180),
                       System.Drawing.Color.FromArgb(223, 133, 61),
                       System.Drawing.Color.FromArgb(150, 170, 210),
                       System.Drawing.Color.FromArgb(207, 145, 144),

                       System.Drawing.Color.FromArgb(60, 109, 162),
                       System.Drawing.Color.FromArgb(163, 61, 58),
                       System.Drawing.Color.FromArgb(131, 159, 68),
                       System.Drawing.Color.FromArgb(105, 80, 133),
                       System.Drawing.Color.FromArgb(56, 144, 170),
                       System.Drawing.Color.FromArgb(213, 123, 51),
                       System.Drawing.Color.FromArgb(140, 160, 200),
                       System.Drawing.Color.FromArgb(200, 135, 134), //#16

                       System.Drawing.Color.FromArgb(200, 70, 119, 172),
                       System.Drawing.Color.FromArgb(200, 173, 71, 68),
                       System.Drawing.Color.FromArgb(200, 141, 169, 78),
                       System.Drawing.Color.FromArgb(200, 115, 90, 143),
                       System.Drawing.Color.FromArgb(200, 66, 154, 180),
                       System.Drawing.Color.FromArgb(200, 223, 133, 61),
                       System.Drawing.Color.FromArgb(200, 150, 170, 210),
                       System.Drawing.Color.FromArgb(200, 207, 145, 144),
                                                     
                       System.Drawing.Color.FromArgb(200, 60, 109, 162),
                       System.Drawing.Color.FromArgb(200, 163, 61, 58),
                       System.Drawing.Color.FromArgb(200, 131, 159, 68),
                       System.Drawing.Color.FromArgb(200, 105, 80, 133),
                       System.Drawing.Color.FromArgb(200, 56, 144, 170),
                       System.Drawing.Color.FromArgb(200, 213, 123, 51),
                       System.Drawing.Color.FromArgb(200, 140, 160, 200),
                       System.Drawing.Color.FromArgb(200, 200, 135, 134) //#32
                       
                };
                #endregion

                #region Front page and Index

                document.NewPage();

                PdfPTable layoutTable = new PdfPTable(new float[] { 50f, 50f });
                layoutTable.WidthPercentage = 100;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.DefaultCell.Padding = 0;

                //Imagen de caratula.

                string path = Path.Combine(ConfigurationManager.AppSettings["ImportersPath"], country.Code, rangeReview.Title, Constants.ImportSettings.ReportsFronPages, country.Code + ".png");

                if (!File.Exists(path))
                {
                    throw new FaultException<ARRExceptionDetail>(new ARRExceptionDetail("Debe agregar una imagen para la caratula en la ruta " + path, ExceptionSeverity.Validation));
                }

                Image img = iTextSharp.text.Image.GetInstance(path);
                img.ScaleToFit(document.PageSize.Width / 2, document.PageSize.Height);
                img.ScaleToFitLineWhenOverflow = true;
                layoutTable.AddCell(img);

                //Tabla para layout de la derecha.
                PdfPTable rightLayout = new PdfPTable(new float[] { 100f });
                rightLayout.WidthPercentage = 100;
                rightLayout.DefaultCell.FixedHeight = document.PageSize.Height / 3;

                Font frontPageFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, new BaseColor(213, 228, 199));
                Font frontPageFontSubtitles = new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, new BaseColor(213, 228, 199));

                rightLayout.DefaultCell.BackgroundColor = new BaseColor(50, 75, 105);
                rightLayout.DefaultCell.PaddingLeft = 50;
                rightLayout.DefaultCell.PaddingTop = 60;

                Paragraph para1 = new Paragraph();
                para1.Font = frontPageFont;
                para1.Add("Category Management  \n");
                para1.Add("Product Range Analysis \n\n");
                Paragraph para1Subtitle = new Paragraph();
                para1Subtitle.Font = frontPageFontSubtitles;
                para1Subtitle.Add(rangeReview.ReportDate.ToString("MMMM yyyy", new CultureInfo("EN-us")));
                para1.Add(para1Subtitle);
                rightLayout.DefaultCell.Border = PdfPCell.NO_BORDER;
                rightLayout.DefaultCell.BorderWidth = 0;
                rightLayout.AddCell(para1);

                Paragraph para2 = new Paragraph();
                para2.Font = frontPageFont;
                para2.Add(category.Name + "\n\n");
                Paragraph para2Subtitle = new Paragraph();
                para2Subtitle.Font = frontPageFontSubtitles;
                para2Subtitle.Add(category.Role != null ? category.Role.Role : string.Empty);
                para2.Add(para2Subtitle);
                rightLayout.DefaultCell.BackgroundColor = new BaseColor(70, 102, 140);
                rightLayout.AddCell(para2);

                Paragraph para3 = new Paragraph();
                para3.Font = frontPageFont;
                para3.Add(rangeReview.Title);
                rightLayout.DefaultCell.BackgroundColor = new BaseColor(107, 132, 163);
                rightLayout.AddCell(para3);
                layoutTable.AddCell(rightLayout);

                document.Add(layoutTable);

                //Index
                ((PageEvent)writer.PageEvent).Title = "Index";
                ((PageEvent)writer.PageEvent).Category = category.Name;
                document.NewPage();

                document.Add(new Paragraph(" "));

                Font indexFont = new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL, new BaseColor(43, 85, 97));

                //Buscar el numero de simbolo que sea un cuadrado o un circulo
                List indexList = new List(List.UNORDERED, 30f);
                indexList.SetListSymbol("\u2022");
                indexList.IndentationLeft = 60f;

                indexList.Add(new ListItem("Same Store Comparison", indexFont));
                indexList.Add(new ListItem("Assortment", indexFont));
                indexList.Add(new ListItem("Product Range Analysis", indexFont));
                if (setup.SpaceAnalysis)
                {
                    indexList.Add(new ListItem("Exhibition Space Analysis", indexFont));
                }
                indexList.Add(new ListItem("Analysis Conclusions", indexFont));

                ListItem appendixItem = new ListItem("Appendix", indexFont);
                List appendixList = new List(List.UNORDERED, 30f);
                appendixList.SetListSymbol("\u2022");
                appendixList.Add(new ListItem("Sales and Margin: Pareto List & Graphics", indexFont));
                if (setup.Penetration)
                {
                    appendixList.Add(new ListItem("SKU Penetration: Top 80% sales", indexFont));
                }
                if (setup.Coverage)
                {
                    appendixList.Add(new ListItem("Store Coverage per SKU: Top 80% sales", indexFont));
                }

                if (setup.DynamicsBrand || setup.DynamicsManufacturer)
                {
                    appendixList.Add(new ListItem("Category Dynamics and Trends", indexFont));
                }
                if (setup.DynamicsManufacturer)
                {
                    appendixList.Add(new ListItem("Manufacturer Current Year vs Prior Year", indexFont));
                }
                if (setup.DynamicsBrand)
                {
                    appendixList.Add(new ListItem("Brand Current Year vs Prior Year", indexFont));
                }
                if (setup.DynamicsBrand || setup.DynamicsManufacturer)
                {
                    appendixList.Add(new ListItem("Inventory Ratios by SKUs", indexFont));
                    appendixList.Add(new ListItem("%GIM by SKU", indexFont));
                }
                appendixList.Add(new ListItem("Profitability per SKU", indexFont));
                if (setup.Space)
                {
                    appendixList.Add(new ListItem("Exhibition Space by SKU", indexFont));
                }
                appendixItem.Add(appendixList);
                indexList.Add(appendixItem);

                document.Add(indexList);

                #endregion

                #region Benchmark


                int count = 1;
                decimal acumSales = 0;
                decimal totalSales = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.Sales);
                decimal totalUnits = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.Units);
                decimal totalGM = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.GM);
                decimal totalSpace = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.LinearSpace);
                decimal totalInventory = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.InventoryCost);
                int totalSKUs = paretoItems.Where(x => !x.IsDeletedRangeReview).Count();

                decimal averageLine = totalSKUs != 0 ? totalSales / totalSKUs : 0;
                decimal averageLineWithoutLeader = 0;
                int averageLineCount = 0;
                decimal acumSKUs = 0;
                int bottom5 = 0;
                foreach (var paretoItem in paretoItems.Where(x => !x.IsDeletedRangeReview))
                {
                    if (count == 1)
                    {
                        averageLineWithoutLeader = (totalSKUs - 1) != 0 ? (totalSales - paretoItem.Sales) / (totalSKUs - 1) : 0;
                    }
                    paretoItem.Ranking = count;
                    paretoItem.PrevAcumSales = totalSales != 0 ? acumSales / totalSales : 0;
                    acumSales += paretoItem.Sales;
                    paretoItem.AcumSales = totalSales != 0 ? acumSales / totalSales : 0;
                    paretoItem.AcumSKUs = totalSKUs != 0 ? count / (decimal)totalSKUs : 0;
                    if (acumSKUs == 0 && (paretoItem.AcumSales >= 0.8m && paretoItem.PrevAcumSales < 0.8m))
                    {
                        acumSKUs = paretoItem.AcumSKUs;
                    }
                    if (paretoItem.AcumSales >= 0.95m)
                    {
                        bottom5++;
                    }
                    if (paretoItem.Sales < averageLine)
                    {
                        averageLineCount++;
                    }

                    count++;
                }

                if (setup.Benchmarks)
                {

                    #region Titulo de la pagina y Headers de la tabla

                    //PageEvent pageEvent = new PageEvent();
                    ((PageEvent)writer.PageEvent).Title = "Category";
                    string subTitle = "Same Store Comparison (vs. ";
                    bool hasPrevious = false;
                    int columnCount = 2;
                    if (salePY != null)
                    {
                        subTitle += "Prior Year";
                        hasPrevious = true;
                        columnCount = columnCount + 2;
                    }
                    if (saleColumn1 != null)
                    {
                        if (hasPrevious)
                        {
                            subTitle += ", ";
                        }
                        subTitle += saleColumn1.Name;
                        hasPrevious = true;
                        columnCount = columnCount + 2;
                    }
                    if (saleColumn2 != null)
                    {
                        if (hasPrevious)
                        {
                            subTitle += ", ";
                        }
                        subTitle += saleColumn2.Name;
                        hasPrevious = true;
                        columnCount = columnCount + 2;
                    }
                    if (saleColumn3 != null)
                    {
                        if (hasPrevious)
                        {
                            subTitle += ", ";
                        }
                        subTitle += saleColumn3.Name;
                        hasPrevious = true;
                        columnCount = columnCount + 2;
                    }
                    subTitle += ")";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = subTitle;
                    ((PageEvent)writer.PageEvent).Category = sale.Category;
                    ((PageEvent)writer.PageEvent).RangeReview = sale.Title;

                    document.NewPage();


                    // step 4

                    document.Add(new Paragraph(" ")); //Para dejar un espacio

                    //Genero una tabla con datos
                    float[] columnRelativeWidths = new float[columnCount];
                    float relativeWidth = 100f / columnCount;
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (i == 0)
                        {
                            columnRelativeWidths.SetValue(relativeWidth * 2, i);
                        }
                        else
                        {
                            columnRelativeWidths.SetValue(relativeWidth, i);
                        }
                    }

                    PdfPTable dataTable = new PdfPTable(columnRelativeWidths);
                    //dataTable.HorizontalAlignment = Element.ALIGN_CENTER;
                    dataTable.WidthPercentage = columnCount < 10 ? columnCount * 10 : 95f;
                    PdfPCell dataheaderCell1 = new PdfPCell(new Phrase(sale.Category, font));
                    dataheaderCell1.BackgroundColor = new BaseColor(184, 204, 228);
                    dataheaderCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                    dataheaderCell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    dataTable.AddCell(dataheaderCell1);

                    PdfPCell dataheaderCell2 = new PdfPCell(new Phrase(sale.Title, font));
                    dataheaderCell2.BackgroundColor = new BaseColor(184, 204, 228);
                    dataheaderCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                    dataheaderCell2.HorizontalAlignment = Element.ALIGN_CENTER;
                    dataTable.AddCell(dataheaderCell2);

                    //Columnas Benchmark
                    if (salePY != null)
                    {
                        PdfPCell dataheaderCellb = new PdfPCell(new Phrase(sale.Title + " PY", font));
                        dataheaderCellb.BackgroundColor = new BaseColor(184, 204, 228);
                        dataheaderCellb.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellb.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellb);
                    }

                    if (saleColumn1 != null)
                    {
                        PdfPCell dataheaderCellb = new PdfPCell(new Phrase(saleColumn1.Name, font));
                        dataheaderCellb.BackgroundColor = new BaseColor(184, 204, 228);
                        dataheaderCellb.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellb.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellb);
                    }

                    if (saleColumn2 != null)
                    {
                        PdfPCell dataheaderCellb = new PdfPCell(new Phrase(saleColumn2.Name, font));
                        dataheaderCellb.BackgroundColor = new BaseColor(184, 204, 228);
                        dataheaderCellb.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellb.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellb);
                    }

                    if (saleColumn3 != null)
                    {
                        PdfPCell dataheaderCellb = new PdfPCell(new Phrase(saleColumn3.Name, font));
                        dataheaderCellb.BackgroundColor = new BaseColor(184, 204, 228);
                        dataheaderCellb.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellb.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellb);
                    }

                    //Columnas comparativas
                    if (salePY != null)
                    {
                        PdfPCell dataheaderCellc = new PdfPCell(new Phrase("Comparison vs. " + sale.Title + " PY", font));
                        dataheaderCellc.BackgroundColor = new BaseColor(219, 229, 241);
                        dataheaderCellc.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellc.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellc);
                    }

                    if (saleColumn1 != null)
                    {
                        PdfPCell dataheaderCellc = new PdfPCell(new Phrase("Comparison vs. " + saleColumn1.Name, font));
                        dataheaderCellc.BackgroundColor = new BaseColor(219, 229, 241);
                        dataheaderCellc.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellc.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellc);
                    }

                    if (saleColumn2 != null)
                    {
                        PdfPCell dataheaderCellc = new PdfPCell(new Phrase("Comparison vs. " + saleColumn2.Name, font));
                        dataheaderCellc.BackgroundColor = new BaseColor(219, 229, 241);
                        dataheaderCellc.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellc.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellc);
                    }

                    if (saleColumn3 != null)
                    {
                        PdfPCell dataheaderCellc = new PdfPCell(new Phrase("Comparison vs. " + saleColumn3.Name, font));
                        dataheaderCellc.BackgroundColor = new BaseColor(219, 229, 241);
                        dataheaderCellc.VerticalAlignment = Element.ALIGN_MIDDLE;
                        dataheaderCellc.HorizontalAlignment = Element.ALIGN_CENTER;
                        dataTable.AddCell(dataheaderCellc);
                    }

                    #endregion

                    #region Sales, Margins, Units
                    //Benchmark Sales
                    if (setup.Sales)
                    {
                        dataTable.AddCell(new Phrase("Sales", font));
                        PdfPCell salesCell = new PdfPCell(new Phrase(sale.Sales.ToString("C0"), font));
                        salesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(salesCell);

                        if (salePY != null)
                        {
                            PdfPCell salesBCell = new PdfPCell(new Phrase(salePY.Sales.ToString("C0"), font));
                            salesBCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesBCell);
                        }

                        if (saleColumn1 != null)
                        {
                            PdfPCell salesBCell = new PdfPCell(new Phrase(saleColumn1.Sales.ToString("C0"), font));
                            salesBCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesBCell);
                        }

                        if (saleColumn2 != null)
                        {
                            PdfPCell salesBCell = new PdfPCell(new Phrase(saleColumn2.Sales.ToString("C0"), font));
                            salesBCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesBCell);
                        }

                        if (saleColumn3 != null)
                        {
                            PdfPCell salesBCell = new PdfPCell(new Phrase(saleColumn3.Sales.ToString("C0"), font));
                            salesBCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesBCell);
                        }

                        //Comparativas Sales
                        if (salePY != null)
                        {
                            decimal result = salePY.Sales != 0 ? sale.Sales / salePY.Sales - 1 : 1;
                            PdfPCell csalesCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            csalesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(csalesCell);
                        }

                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.Sales != 0 ? sale.Sales / saleColumn1.Sales - 1 : 1;
                            PdfPCell csalesCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            csalesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(csalesCell);
                        }

                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.Sales != 0 ? sale.Sales / saleColumn2.Sales - 1 : 1;
                            PdfPCell csalesCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            csalesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(csalesCell);
                        }

                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.Sales != 0 ? sale.Sales / saleColumn3.Sales - 1 : 1;
                            PdfPCell csalesCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            csalesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(csalesCell);
                        }

                        //Benchmark % of Total Store
                        dataTable.AddCell(new Phrase("  % of Total Store", font));
                        PdfPCell salesPCell = new PdfPCell(new Phrase(sale.SalesShare.ToString("P1"), font));
                        salesPCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(salesPCell);

                        if (salePY != null)
                        {
                            PdfPCell salesShareCell = new PdfPCell(new Phrase(salePY.SalesShare.ToString("P1"), font));
                            salesShareCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesShareCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell salesShareCell = new PdfPCell(new Phrase(saleColumn1.SalesShare.ToString("P1"), font));
                            salesShareCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesShareCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell salesShareCell = new PdfPCell(new Phrase(saleColumn2.SalesShare.ToString("P1"), font));
                            salesShareCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesShareCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell salesShareCell = new PdfPCell(new Phrase(saleColumn3.SalesShare.ToString("P1"), font));
                            salesShareCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(salesShareCell);
                        }

                        //Comparativas % of Total Store
                        if (salePY != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn1 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn2 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn3 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    //Benchmark GI Margin
                    if (setup.Margin)
                    {
                        dataTable.AddCell(new Phrase("GI Margin", font));
                        PdfPCell gmCell = new PdfPCell(new Phrase(sale.GM.ToString("C0"), font));
                        gmCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(gmCell);

                        if (salePY != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(salePY.GM.ToString("C0"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn1 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn1.GM.ToString("C0"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn2 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn2.GM.ToString("C0"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn3 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn3.GM.ToString("C0"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        //Comparativas GI Margin
                        if (salePY != null)
                        {
                            decimal result = salePY.GM != 0 ? (sale.GM / salePY.GM - 1) : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.GM != 0 ? (sale.GM / saleColumn1.GM - 1) : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.GM != 0 ? (sale.GM / saleColumn2.GM - 1) : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.GM != 0 ? (sale.GM / saleColumn3.GM - 1) : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }


                        // Benchmark % of Total Store GM
                        dataTable.AddCell(new Phrase("  % of Total Store", font));
                        PdfPCell gmPCell = new PdfPCell(new Phrase(sale.GMShare.ToString("P1"), font));
                        gmPCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(gmPCell);
                        if (salePY != null)
                        {
                            PdfPCell gmPPYCell = new PdfPCell(new Phrase(salePY.GMShare.ToString("P1"), font));
                            gmPPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell gmPPYCell = new PdfPCell(new Phrase(saleColumn1.GMShare.ToString("P1"), font));
                            gmPPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell gmPPYCell = new PdfPCell(new Phrase(saleColumn2.GMShare.ToString("P1"), font));
                            gmPPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell gmPPYCell = new PdfPCell(new Phrase(saleColumn3.GMShare.ToString("P1"), font));
                            gmPPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPPYCell);
                        }

                        //Comparativos % of Total Store GM
                        if (salePY != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn1 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn2 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }
                        if (saleColumn3 != null)
                        {
                            dataTable.AddCell(new Phrase(string.Empty));
                        }

                        //Benchmark GI Margin %

                        dataTable.AddCell(new Phrase("GI Margin %", font));
                        PdfPCell gmPercentCell = new PdfPCell(new Phrase(sale.GMPercent.ToString("P1"), font));
                        gmPercentCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(gmPercentCell);

                        if (salePY != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(salePY.GMPercent.ToString("P1"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn1 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn1.GMPercent.ToString("P1"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn2 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn2.GMPercent.ToString("P1"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        if (saleColumn3 != null)
                        {
                            PdfPCell gmPYCell = new PdfPCell(new Phrase(saleColumn3.GMPercent.ToString("P1"), font));
                            gmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(gmPYCell);
                        }

                        //Comparativas GI Margin %
                        if (salePY != null)
                        {
                            decimal result = salePY.GMPercent != 0 ? sale.GMPercent / salePY.GMPercent - 1 : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.GMPercent != 0 ? sale.GMPercent / saleColumn1.GMPercent - 1 : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.GMPercent != 0 ? sale.GMPercent / saleColumn2.GMPercent - 1 : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.GMPercent != 0 ? sale.GMPercent / saleColumn3.GMPercent - 1 : 1;
                            PdfPCell cgmPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cgmPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cgmPYCell);
                        }

                    }

                    if (setup.Units)
                    {
                        //Benchmark Units
                        dataTable.AddCell(new Phrase("Sales Units", font));
                        PdfPCell unitsCell = new PdfPCell(new Phrase(sale.Units.ToString("N0"), font));
                        unitsCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(unitsCell);
                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.Units.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.Units.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.Units.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.Units.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Units
                        if (salePY != null)
                        {
                            decimal result = salePY.Units != 0 ? sale.Units / salePY.Units - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.Units != 0 ? sale.Units / saleColumn1.Units - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.Units != 0 ? sale.Units / saleColumn2.Units - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.Units != 0 ? sale.Units / saleColumn3.Units - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                    }

                    //Agrego una fila vacia y sin bordes
                    emptyTableCell.Colspan = columnCount;
                    dataTable.AddCell(emptyTableCell);
                    #endregion

                    #region Inventory
                    if (setup.Inventory)
                    {
                        //Benchmark Inventories
                        dataTable.AddCell(new Phrase("Inventory", font));
                        PdfPCell unitsCell = new PdfPCell(new Phrase(sale.InventoryCost.ToString("C0"), font));
                        unitsCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(unitsCell);
                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.InventoryCost.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.InventoryCost.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.InventoryCost.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.InventoryCost.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Inventories
                        if (salePY != null)
                        {
                            decimal result = salePY.InventoryCost != 0 ? sale.InventoryCost / salePY.InventoryCost - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.InventoryCost != 0 ? sale.InventoryCost / saleColumn1.InventoryCost - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.InventoryCost != 0 ? sale.InventoryCost / saleColumn2.InventoryCost - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.InventoryCost != 0 ? sale.InventoryCost / saleColumn3.InventoryCost - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark Inv Days
                        dataTable.AddCell(new Phrase("Inv Days", font));
                        PdfPCell invDayscell = new PdfPCell(new Phrase(sale.InvDays.ToString("N0"), font));
                        invDayscell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(invDayscell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.InvDays.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.InvDays.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.InvDays.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.InvDays.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Inv Days
                        if (salePY != null)
                        {
                            decimal result = salePY.InvDays != 0 ? sale.InvDays / salePY.InvDays - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.InvDays != 0 ? sale.InvDays / saleColumn1.InvDays - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.InvDays != 0 ? sale.InvDays / saleColumn2.InvDays - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.InvDays != 0 ? sale.InvDays / saleColumn3.InvDays - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark Annual Stock Turns
                        dataTable.AddCell(new Phrase("Annual Stock Turn", font));
                        PdfPCell turnCell = new PdfPCell(new Phrase(sale.AnnualStockTurn.ToString("N0"), font));
                        turnCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(turnCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.AnnualStockTurn.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.AnnualStockTurn.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.AnnualStockTurn.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.AnnualStockTurn.ToString("N0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Annual Stock Turns
                        if (salePY != null)
                        {
                            decimal result = salePY.AnnualStockTurn != 0 ? sale.AnnualStockTurn / salePY.AnnualStockTurn - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.AnnualStockTurn != 0 ? sale.AnnualStockTurn / saleColumn1.AnnualStockTurn - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.AnnualStockTurn != 0 ? sale.AnnualStockTurn / saleColumn2.AnnualStockTurn - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.AnnualStockTurn != 0 ? sale.AnnualStockTurn / saleColumn3.AnnualStockTurn - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark GMROI
                        dataTable.AddCell(new Phrase("GMROI", font));
                        PdfPCell gmroiCell = new PdfPCell(new Phrase(sale.GMROI.ToString("N2"), font));
                        gmroiCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(gmroiCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.GMROI.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.GMROI.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.GMROI.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.GMROI.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos GMROI
                        if (salePY != null)
                        {
                            decimal result = salePY.GMROI != 0 ? sale.GMROI / salePY.GMROI - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.GMROI != 0 ? sale.GMROI / saleColumn1.GMROI - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.GMROI != 0 ? sale.GMROI / saleColumn2.GMROI - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.GMROI != 0 ? sale.GMROI / saleColumn3.GMROI - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }


                        //Agrego una fila vacia y sin bordes
                        emptyTableCell.Colspan = columnCount;
                        dataTable.AddCell(emptyTableCell);
                    }
                    #endregion

                    #region Spaces

                    //Si tengo Range Review Anterior traigo la data del RR anterior
                    int totalSKUsPRR = 0;
                    decimal skus80PRR = 0;
                    decimal? totalSpacePRR = null;
                    decimal? totalSalesOverSpacePRR = null;
                    decimal? totalGMROSPRR = null;
                    if (rangeReview.PYHistoryId.HasValue)
                    {
                        var prrRows = HistoryDetailsRepository.Select(x => x.HistoryId == rangeReview.PYHistoryId.Value && x.CategoryId == categoryId);
                        var prr = prrRows.ConvertAll<HistoryDetail>(c => new HistoryDetail(c)).FirstOrDefault();
                        if (prr != null)
                        {
                            totalSpacePRR = prr.Space;
                            totalSalesOverSpacePRR = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? salePY.Sales / totalSpacePRR : null;
                            totalGMROSPRR = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? salePY.GM / totalSpacePRR : null;
                            totalSKUsPRR = prr.SKUsWithSales.HasValue ? prr.SKUsWithSales.Value : 0;
                            skus80PRR = prr.Sales80.HasValue && prr.SKUsWithSales.HasValue && prr.SKUsWithSales.Value != 0 ? (decimal)prr.Sales80.Value / prr.SKUsWithSales.Value : 0;
                        }
                    }

                    if (setup.Space)
                    {
                        //Benchmark Spaces
                        dataTable.AddCell(new Phrase("Space (mt.)", font));
                        PdfPCell spacesCell = new PdfPCell(new Phrase(sale.LinearSpace.ToString("N2"), font));
                        spacesCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(spacesCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? totalSpacePRR.Value.ToString("N2") : string.Empty, font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.LinearSpace.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.LinearSpace.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.LinearSpace.ToString("N2"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Spaces
                        if (salePY != null)
                        {
                            decimal result = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? sale.LinearSpace / totalSpacePRR.Value - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.LinearSpace != 0 ? sale.LinearSpace / saleColumn1.LinearSpace - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.LinearSpace != 0 ? sale.LinearSpace / saleColumn2.LinearSpace - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.LinearSpace != 0 ? sale.LinearSpace / saleColumn3.LinearSpace - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark Sales / Linear mt
                        dataTable.AddCell(new Phrase("Sales / Linear mt", font));
                        PdfPCell salesOverMeterCell = new PdfPCell(new Phrase(sale.SalesOverLinearMt.ToString("C0"), font));
                        salesOverMeterCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(salesOverMeterCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(totalSalesOverSpacePRR.HasValue ? totalSalesOverSpacePRR.Value.ToString("C0") : string.Empty, font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.SalesOverLinearMt.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.SalesOverLinearMt.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.SalesOverLinearMt.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Sales / Linear mt
                        if (salePY != null)
                        {
                            //decimal result = salePY.SalesOverLinearMt != 0 ? (sale.SalesOverLinearMt / salePY.SalesOverLinearMt - 1) : 1;
                            decimal result = totalSalesOverSpacePRR.HasValue && totalSalesOverSpacePRR.Value != 0 ? sale.SalesOverLinearMt / totalSalesOverSpacePRR.Value - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.SalesOverLinearMt != 0 ? (sale.SalesOverLinearMt / saleColumn1.SalesOverLinearMt - 1) : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.SalesOverLinearMt != 0 ? (sale.SalesOverLinearMt / saleColumn2.SalesOverLinearMt - 1) : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.SalesOverLinearMt != 0 ? (sale.SalesOverLinearMt / saleColumn3.SalesOverLinearMt - 1) : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark GMROS
                        dataTable.AddCell(new Phrase("GMROS", font));
                        PdfPCell gmrosCell = new PdfPCell(new Phrase(sale.GMROS.ToString("C0"), font));
                        gmrosCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(gmrosCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(totalGMROSPRR.HasValue ? totalGMROSPRR.Value.ToString("C0") : string.Empty, font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.GMROS.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.GMROS.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.GMROS.ToString("C0"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos GMROS
                        if (salePY != null)
                        {
                            decimal result = totalGMROSPRR.HasValue && totalGMROSPRR.Value != 0 ? sale.GMROS / totalGMROSPRR.Value - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.GMROS != 0 ? sale.GMROS / saleColumn1.GMROS - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.GMROS != 0 ? sale.GMROS / saleColumn2.GMROS - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.GMROS != 0 ? sale.GMROS / saleColumn3.GMROS - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }


                        //Agrego una fila vacia y sin bordes
                        emptyTableCell.Colspan = columnCount;
                        dataTable.AddCell(emptyTableCell);
                    }
                    #endregion

                    #region SKUs
                    if (setup.SKUs)
                    {
                        //Benchmark SKUs
                        dataTable.AddCell(new Phrase("SKUs", font));
                        PdfPCell skusCell = new PdfPCell(new Phrase(totalSKUs.ToString("N0"), font));
                        skusCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(skusCell);

                        if (salePY != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(totalSKUsPRR != 0 ? totalSKUsPRR.ToString("N0") : string.Empty, font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn1.SKUs.ToString("N0"), font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn2.SKUs.ToString("N0"), font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn3.SKUs.ToString("N0"), font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }

                        //Comparativos SKUs
                        if (salePY != null)
                        {
                            decimal result = totalSKUsPRR != 0 ? (decimal)totalSKUs / totalSKUsPRR - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.SKUs != 0 ? (decimal)totalSKUs / saleColumn1.SKUs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.SKUs != 0 ? (decimal)totalSKUs / saleColumn2.SKUs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.SKUs != 0 ? (decimal)totalSKUs / saleColumn3.SKUs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark SKUs with 80%
                        dataTable.AddCell(new Phrase("SKUs with 80% of sales", font));
                        PdfPCell skus80Cell = new PdfPCell(new Phrase(acumSKUs.ToString("P1"), font));
                        skus80Cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(skus80Cell);

                        if (salePY != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(skus80PRR != 0 ? skus80PRR.ToString("P1") : string.Empty, font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn1.SKUs != 0 ? ((decimal)saleColumn1.Sales80 / saleColumn1.SKUs).ToString("P1") : "100 %", font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn2.SKUs != 0 ? ((decimal)saleColumn2.Sales80 / saleColumn2.SKUs).ToString("P1") : "100 %", font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell skusPYCell = new PdfPCell(new Phrase(saleColumn3.SKUs != 0 ? ((decimal)saleColumn3.Sales80 / saleColumn3.SKUs).ToString("P1") : "100 %", font));
                            skusPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(skusPYCell);
                        }

                        //Comparativos SKUs 80%
                        if (salePY != null)
                        {
                            decimal result = skus80PRR != 0 ? acumSKUs / skus80PRR - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = 1;

                            if (saleColumn1.Sales80 != 0 && saleColumn1.SKUs != 0)
                            {
                                result = (acumSKUs / ((decimal)saleColumn1.Sales80 / saleColumn1.SKUs) - 1);
                            }
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = 1;

                            if (saleColumn2.Sales80 != 0 && saleColumn2.SKUs != 0)
                            {
                                result = (acumSKUs / ((decimal)saleColumn2.Sales80 / saleColumn2.SKUs) - 1);
                            }

                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = 1;

                            if (saleColumn3.Sales80 != 0 && saleColumn3.SKUs != 0)
                            {
                                result = (acumSKUs / ((decimal)saleColumn3.Sales80 / saleColumn3.SKUs) - 1);
                            }
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Agrego una fila vacia y sin bordes
                        emptyTableCell.Colspan = columnCount;
                        dataTable.AddCell(emptyTableCell);
                    }
                    #endregion

                    #region PI Differences
                    if (setup.PIDiff)
                    {
                        //Benchmark PI Differences
                        dataTable.AddCell(new Phrase("PI Differences", font));
                        PdfPCell piDiffCell = new PdfPCell(new Phrase(sale.PIDiff.ToString("P1"), font));
                        piDiffCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(piDiffCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.PIDiff.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.PIDiff.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.PIDiff.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.PIDiff.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos PI Differences
                        if (salePY != null)
                        {
                            decimal result = salePY.PIDiff != 0 ? sale.PIDiff / salePY.PIDiff - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.PIDiff != 0 ? sale.PIDiff / saleColumn1.PIDiff - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.PIDiff != 0 ? sale.PIDiff / saleColumn2.PIDiff - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.PIDiff != 0 ? sale.PIDiff / saleColumn3.PIDiff - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Benchmark ChargeOffs
                        dataTable.AddCell(new Phrase("Charge Off", font));
                        PdfPCell chargeOffsCell = new PdfPCell(new Phrase(sale.ChargeOffs.ToString("P1"), font));
                        chargeOffsCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(chargeOffsCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.ChargeOffs.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.ChargeOffs.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.ChargeOffs.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.ChargeOffs.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos ChargeOffs
                        if (salePY != null)
                        {
                            decimal result = salePY.ChargeOffs != 0 ? sale.ChargeOffs / salePY.ChargeOffs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.ChargeOffs != 0 ? sale.ChargeOffs / saleColumn1.ChargeOffs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.ChargeOffs != 0 ? sale.ChargeOffs / saleColumn2.ChargeOffs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.ChargeOffs != 0 ? sale.ChargeOffs / saleColumn3.ChargeOffs - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }


                        //Benchmark Actual Margin
                        dataTable.AddCell(new Phrase("Actual Margin %", font));
                        PdfPCell actualMarginCell = new PdfPCell(new Phrase(sale.ActualMargin.ToString("P1"), font));
                        actualMarginCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        dataTable.AddCell(actualMarginCell);

                        if (salePY != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(salePY.ActualMargin.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn1.ActualMargin.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn2.ActualMargin.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            PdfPCell unitsPYCell = new PdfPCell(new Phrase(saleColumn3.ActualMargin.ToString("P1"), font));
                            unitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(unitsPYCell);
                        }

                        //Comparativos Actual Margin
                        if (salePY != null)
                        {
                            decimal result = salePY.ActualMargin != 0 ? sale.ActualMargin / salePY.ActualMargin - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn1 != null)
                        {
                            decimal result = saleColumn1.ActualMargin != 0 ? sale.ActualMargin / saleColumn1.ActualMargin - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn2 != null)
                        {
                            decimal result = saleColumn2.ActualMargin != 0 ? sale.ActualMargin / saleColumn2.ActualMargin - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }
                        if (saleColumn3 != null)
                        {
                            decimal result = saleColumn3.ActualMargin != 0 ? sale.ActualMargin / saleColumn3.ActualMargin - 1 : 1;
                            PdfPCell cunitsPYCell = new PdfPCell(new Phrase(result.ToString("P1"), font));
                            cunitsPYCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            dataTable.AddCell(cunitsPYCell);
                        }

                        //Agrego una fila vacia y sin bordes
                        emptyTableCell.Colspan = columnCount;
                        dataTable.AddCell(emptyTableCell);
                    }
                    #endregion

                    document.Add(dataTable);
                }
                #endregion

                #region Assortment
                ((PageEvent)writer.PageEvent).Title = "Assortment";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Main Sales Indicators";

                document.NewPage();

                Font font16 = new Font(Calibri, 16, Font.NORMAL, BaseColor.BLACK);
                Font font12 = new Font(Calibri, 12, Font.NORMAL, BaseColor.BLACK);
                Font font30 = new Font(Calibri, 30, Font.NORMAL, BaseColor.BLUE);
                Font font13blue = new Font(Calibri, 13, Font.BOLD, BaseColor.BLUE);
                Font font13bold = new Font(Calibri, 13, Font.BOLD, BaseColor.BLACK);
                Font font10white = new Font(Calibri, 10, Font.BOLD, BaseColor.WHITE);
                Font font10 = new Font(Calibri, 10, Font.NORMAL, BaseColor.BLACK);
                Font font10bold = new Font(Calibri, 10, Font.BOLD, BaseColor.BLACK);
                Font font10blue = new Font(Calibri, 10, Font.NORMAL, BaseColor.BLUE);
                Font font9bold = new Font(Calibri, 9, Font.BOLD, BaseColor.BLACK);
                Font font9 = new Font(Calibri, 9, Font.NORMAL, BaseColor.BLACK);

                Paragraph p1 = new Paragraph();
                p1.SpacingBefore = 100f;
                p1.IndentationLeft = 100f;
                p1.IndentationRight = 50f;
                p1.Add(new Phrase(string.Format("80 % of total Category Sales come from {0} of the range", acumSKUs.ToString("P0")), font16));
                document.Add(p1);

                Paragraph p2 = new Paragraph();
                p2.SpacingBefore = 20f;
                p2.IndentationLeft = 100f;
                p2.IndentationRight = 50f;
                p2.Add(new Phrase(string.Format("The bottom 5 % in sales is represented by {0} SKUs", bottom5), font16));
                document.Add(p2);

                Paragraph p3 = new Paragraph();
                p3.SpacingBefore = 20f;
                p3.IndentationLeft = 100f;
                p3.IndentationRight = 50f;
                p3.Add(new Phrase(string.Format("The AL is {0} ({1} SKUs performed below it)", averageLine.ToString("C0"), averageLineCount), font16));
                document.Add(p3);

                Paragraph p4 = new Paragraph();
                p4.IndentationLeft = 150f;
                p4.IndentationRight = 50f;
                p4.Add(new Phrase(string.Format("AL without leader is: {0}", averageLineWithoutLeader.ToString("C0")), font16));
                document.Add(p4);

                Paragraph p5 = new Paragraph();
                p5.IndentationLeft = 150f;
                p5.IndentationRight = 50f;
                p5.Add(new Phrase(string.Format("Category Leader is: {0}", paretoItems.Where(x => !x.IsDeletedRangeReview).First().Name), font16));
                document.Add(p5);

                Paragraph p6 = new Paragraph();
                p6.SpacingBefore = 20f;
                p6.IndentationLeft = 100f;
                p6.IndentationRight = 50f;
                decimal p6Result = totalUnits != 0 ? totalSales / totalUnits : 0;
                p6.Add(new Phrase(string.Format("The Avg. Price is: {0}", p6Result.ToString("C2")), font16));
                document.Add(p6);

                Paragraph p7 = new Paragraph();
                p7.SpacingBefore = 20f;
                p7.IndentationLeft = 100f;
                p7.IndentationRight = 50f;
                decimal p7Result = totalSKUs != 0 ? totalUnits / totalSKUs : 0;
                p7.Add(new Phrase(string.Format("Product turn is: {0} units/SKUs", p7Result.ToString("N0")), font16));
                document.Add(p7);

                Paragraph p8 = new Paragraph();
                p8.SpacingBefore = 100f;
                p8.IndentationLeft = 500f;
                p8.IndentationRight = 20f;
                p8.Add(new Phrase(string.Format("Average Line (AL) = {0} Sales / # SKUs", currencySymbol), font12));
                document.Add(p8);

                Paragraph p9 = new Paragraph();
                p9.IndentationLeft = 500f;
                p9.IndentationRight = 20f;
                p9.Add(new Phrase("Product Turn (Turn) = Volume Sales / # SKUs", font12));
                document.Add(p9);

                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                Paragraph caratula1 = new Paragraph();
                caratula1.SpacingBefore = 180f;
                caratula1.IndentationLeft = 100f;
                caratula1.IndentationRight = 20f;
                caratula1.Add(new Phrase("Product Range Analysis", font30));
                document.Add(caratula1);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Product Range Analysis
                int included = 4;

                //Calculo los Totales que son los mismos para todas las segmentaciones
                //Linea con Totales
                PdfPTable totalTable = new PdfPTable(13);

                PdfPCell totalCellData = new PdfPCell(new Phrase(""));
                totalCellData.BackgroundColor = new BaseColor(184, 204, 228);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(paretoItems.Where(x => !x.IsDeletedRangeReview && x.AcumSales >= 0.95m).Count().ToString("N0"), fontRed);
                totalCellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalSKUs.ToString("N0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalUnits.ToString("N0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalSales.ToString("C0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalGM.ToString("C0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalSpace.ToString("N2"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase((totalSales / totalSKUs).ToString("C0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase((totalUnits / totalSKUs).ToString("N0"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase((totalSales / totalUnits).ToString("C2"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase((totalGM / totalSales).ToString("P1"), font);
                totalTable.AddCell(totalCellData);

                totalCellData.Phrase = new Phrase(totalSpace != 0 ? (totalGM / totalSpace).ToString("C0") : string.Empty, font);
                totalTable.AddCell(totalCellData);

                decimal totalInvDays = totalInventory != 0 ? totalInventory / ((totalSales - totalGM) / 30) : 0;
                totalCellData.Phrase = new Phrase(totalInvDays.ToString("N0"), font);
                totalTable.AddCell(totalCellData);

                PdfPCell emptyCell = new PdfPCell(new Phrase(" ", font10blue));
                emptyCell.BorderWidth = 0;
                emptyCell.Colspan = 13;

                #region SubCategory
                if (setup.Subcategory)
                {
                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Performance by Subcategory";

                    document.NewPage();

                    RadChart chartSubcategory = ReportsHelper.GetBarsChart("% Shares by Subcategory"); //new RadChart();
                    chartSubcategory.Width = 750;
                    chartSubcategory.Height = 350;
                    chartSubcategory.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartSubcategory.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    //Sumarizo por Subcategoria
                    int totalSubCats = paretoItems.Where(x => !x.IsDeletedRangeReview).Select(x => x.Subcategory).Distinct(StringComparer.CurrentCultureIgnoreCase).Count();
                    int limit = totalSubCats > included ? included : totalSubCats;

                    var subCategories = (from item in paretoItems
                                         where !item.IsDeletedRangeReview
                                         group item by item.Subcategory into g
                                         orderby g.Sum(x => x.Sales) descending
                                         select new
                                         {
                                             Subcategory = g.Key,
                                             UnitsP = totalUnits != 0 ? g.Sum(x => x.Units) / totalUnits : 0,
                                             SalesP = totalSales != 0 ? g.Sum(x => x.Sales) / totalSales : 0,
                                             GmP = totalGM != 0 ? g.Sum(x => x.GM) / totalGM : 0,
                                             SKUsP = totalSKUs != 0 ? g.Count() / (decimal)totalSKUs : 0,
                                             SpaceP = totalSpace != 0 ? g.Sum(x => x.LinearSpace) / totalSpace : 0,
                                             Units = g.Sum(x => x.Units),
                                             Sales = g.Sum(x => x.Sales),
                                             Gm = g.Sum(x => x.GM),
                                             SKUs = g.Count(),
                                             Space = g.Sum(x => x.LinearSpace),
                                         }).ToList();

                    var subCategoriesAndOthers = subCategories.Take(limit).ToList();
                    if (totalSubCats > included)
                    {
                        subCategoriesAndOthers.Add(
                            new
                            {
                                Subcategory = "Others",
                                UnitsP = totalUnits != 0 ? decimal.Round(subCategories.Skip(limit).Sum(x => x.Units) / totalUnits, 2) : 0,
                                SalesP = totalSales != 0 ? decimal.Round(subCategories.Skip(limit).Sum(x => x.Sales) / totalSales, 2) : 0,
                                GmP = totalGM != 0 ? decimal.Round(subCategories.Skip(limit).Sum(x => x.Gm) / totalGM, 2) : 0,
                                SKUsP = totalSKUs != 0 ? decimal.Round(subCategories.Skip(limit).Sum(x => x.SKUs) / (decimal)totalSKUs, 2) : 0,
                                SpaceP = totalSpace != 0 ? decimal.Round(subCategories.Skip(limit).Sum(x => x.Space) / totalSpace, 2) : 0,
                                Units = decimal.Round(subCategories.Skip(limit).Sum(x => x.Units), 2),
                                Sales = decimal.Round(subCategories.Skip(limit).Sum(x => x.Sales), 2),
                                Gm = decimal.Round(subCategories.Skip(limit).Sum(x => x.Gm), 2),
                                SKUs = subCategories.Skip(limit).Sum(x => x.SKUs),
                                Space = decimal.Round(subCategories.Skip(limit).Sum(x => x.Space), 2),
                            });
                    }

                    int colorCount = 0;
                    foreach (var item in subCategoriesAndOthers)
                    {
                        ChartSeries subcategoriesSeries = new ChartSeries(item.Subcategory);
                        subcategoriesSeries.Type = ChartSeriesType.StackedBar100;
                        subcategoriesSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        subcategoriesSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        subcategoriesSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        subcategoriesSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        subcategoriesSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        subcategoriesSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem subcategoryItem = new ChartSeriesItem();
                        subcategoryItem.YValue = (double)item.SalesP;
                        subcategoryItem.Label.TextBlock.Text = (item.SalesP * 100).ToString("N0");
                        subcategoryItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        subcategoryItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        subcategoryItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        subcategoriesSeries.AddItem(subcategoryItem);

                        //GIM
                        ChartSeriesItem subcategoryGMItem = new ChartSeriesItem();
                        subcategoryGMItem.YValue = (double)item.GmP;
                        subcategoryGMItem.Label.TextBlock.Text = (item.GmP * 100).ToString("N0");
                        subcategoryGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        subcategoryGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        subcategoryGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        subcategoriesSeries.AddItem(subcategoryGMItem);

                        //Units
                        ChartSeriesItem subcategoryUnitsItem = new ChartSeriesItem();
                        subcategoryUnitsItem.YValue = (double)item.UnitsP;
                        subcategoryUnitsItem.Label.TextBlock.Text = (item.UnitsP * 100).ToString("N0");
                        subcategoryUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        subcategoryUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        subcategoryUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        subcategoriesSeries.AddItem(subcategoryUnitsItem);

                        //SKUs
                        ChartSeriesItem subcategorySKUsItem = new ChartSeriesItem();
                        subcategorySKUsItem.YValue = (double)item.SKUsP;
                        subcategorySKUsItem.Label.TextBlock.Text = (item.SKUsP * 100).ToString("N0");
                        subcategorySKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        subcategorySKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        subcategorySKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        subcategoriesSeries.AddItem(subcategorySKUsItem);

                        if (setup.Space)
                        {
                            //Space
                            ChartSeriesItem subcategorySpaceItem = new ChartSeriesItem();
                            subcategorySpaceItem.YValue = (double)item.SpaceP;
                            subcategorySpaceItem.Label.TextBlock.Text = (item.SpaceP * 100).ToString("N0");
                            subcategorySpaceItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                            subcategorySpaceItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                            subcategorySpaceItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                            subcategoriesSeries.AddItem(subcategorySpaceItem);
                        }

                        chartSubcategory.Series.Add(subcategoriesSeries);
                    }

                    if (chartSubcategory.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartSubcategory.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartSubcategory.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartSubcategory.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartSubcategory.PlotArea.XAxis[3].TextBlock.Text = "% # SKUs";
                        if (setup.Space)
                        {
                            chartSubcategory.PlotArea.XAxis[4].TextBlock.Text = "% Space";
                        }
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartSubcategory.PlotArea.XAxis.Clear();
                        chartSubcategory.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartSubcategory.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartSubcategory.PlotArea.XAxis.AddItem("% Units");
                        chartSubcategory.PlotArea.XAxis.AddItem("% # SKUs");
                        if (setup.Space)
                        {
                            chartSubcategory.PlotArea.XAxis.AddItem("% Space");
                        }
                    }


                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartSubcategory.GetBitmap(), BaseColor.WHITE);
                    chartImg.Alignment = 1;
                    chartImg.IndentationLeft = 10f;
                    document.Add(chartImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable subCategoryTable = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1.3f, 1.3f, 1f, 1f, 1f, 1f, 1f, 1f, 1f });
                    subCategoryTable.WidthPercentage = 95f;

                    subCategoryTable.AddCell(emptyCell);

                    PdfPCell subCategoryHeaderCell = new PdfPCell(new Phrase("Subcategory", font));
                    subCategoryHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    subCategoryHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    subCategoryHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Bottom 5%", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("# SKUs", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Volume", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Space(mt.)", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    PdfPCell subCategoryHeaderCell2 = new PdfPCell(new Phrase("AL", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    subCategoryTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("Turns", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    subCategoryTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("Avg. Price", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    subCategoryTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("% GIM", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    subCategoryTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell.Phrase = new Phrase("GMROS", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Inv Days", font);
                    subCategoryTable.AddCell(subCategoryHeaderCell);

                    if (totalSubCats > 8)
                    {
                        subCategoryTable.AddCell(emptyCell);
                        subCategoryTable.AddCell(emptyCell);
                        subCategoryTable.AddCell(emptyCell);
                        subCategoryTable.AddCell(emptyCell);
                    }

                    decimal bottomFive, skus, volume, scSales, gm, space, al, turns, averagePrice, gmPercent, gmros, invDays, inventoryCost;

                    foreach (var subcategory in subCategories)
                    {
                        bottomFive = paretoItems.Where(x => !x.IsDeletedRangeReview && x.AcumSales >= 0.95m && x.Subcategory == subcategory.Subcategory).Count();
                        skus = subcategory.SKUs;
                        volume = subcategory.Units;
                        scSales = subcategory.Sales;
                        gm = subcategory.Gm;
                        space = subcategory.Space;
                        al = skus != 0 ? scSales / skus : 0;
                        turns = skus != 0 ? volume / skus : 0;
                        averagePrice = volume != 0 ? scSales / volume : 0;
                        gmPercent = scSales != 0 ? gm / scSales : 0;
                        gmros = space != 0 ? gm / space : 0;
                        inventoryCost = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory.Subcategory).Sum(x => x.InventoryCost);
                        invDays = (scSales - gm) != 0 ? inventoryCost / ((scSales - gm) / 30) : 0;

                        subCategoryTable.AddCell(new PdfPCell(new Phrase(subcategory.Subcategory, font)));

                        PdfPCell cellData = new PdfPCell(new Phrase(bottomFive.ToString(), fontRed));
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(skus.ToString(), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(volume.ToString("N0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(scSales.ToString("C0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gm.ToString("C0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(space.ToString("N2"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(al.ToString("C0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(turns.ToString("N0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(averagePrice.ToString("C2"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmPercent.ToString("P1"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmros.ToString("C0"), font);
                        subCategoryTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(invDays.ToString("N0"), font);
                        subCategoryTable.AddCell(cellData);
                    }

                    foreach (var cell in totalTable.GetRow(0).GetCells())
                    {
                        subCategoryTable.AddCell(cell);
                    }

                    //La tabla se banca hasta 8 filas en la misma hoja. Si no va a una hoja aparte
                    if (totalSubCats > 8)
                    {
                        subCategoryTable.HeaderRows = 6;
                        subCategoryTable.FooterRows = 4;

                        document.NewPage();
                    }
                    else
                    {
                        subCategoryTable.Rows.RemoveAt(0);
                    }
                    document.Add(subCategoryTable);
                }
                #endregion

                #region Brand

                if (setup.Brand)
                {
                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Performance by Brand";

                    document.NewPage();

                    RadChart chartBrand = ReportsHelper.GetBarsChart("% Shares by Brand");
                    chartBrand.Width = 750;
                    chartBrand.Height = 350;
                    chartBrand.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartBrand.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    //Sumarizo por Subcategoria
                    int totalBrands = paretoItems.Where(x => !x.IsDeletedRangeReview).Select(x => x.Brand).Distinct(StringComparer.CurrentCultureIgnoreCase).Count();
                    int limit = totalBrands > included ? included : totalBrands;

                    var brands = (from item in paretoItems
                                  where !item.IsDeletedRangeReview
                                  group item by item.Brand.ToUpper() into g
                                  orderby g.Sum(x => x.Sales) descending
                                  select new
                                  {
                                      Brand = g.Key,
                                      UnitsP = totalUnits != 0 ? g.Sum(x => x.Units) / totalUnits : 0,
                                      SalesP = totalSales != 0 ? g.Sum(x => x.Sales) / totalSales : 0,
                                      GmP = totalGM != 0 ? g.Sum(x => x.GM) / totalGM : 0,
                                      SKUsP = totalSKUs != 0 ? g.Count() / (decimal)totalSKUs : 0,
                                      SpaceP = totalSpace != 0 ? g.Sum(x => x.LinearSpace) / totalSpace : 0,
                                      Units = g.Sum(x => x.Units),
                                      Sales = g.Sum(x => x.Sales),
                                      Gm = g.Sum(x => x.GM),
                                      SKUs = g.Count(),
                                      Space = g.Sum(x => x.LinearSpace)
                                  }).ToList();

                    var brandsAndOthers = brands.Take(limit).ToList();
                    if (totalBrands > included)
                    {
                        brandsAndOthers.Add(
                            new
                            {
                                Brand = "Others",
                                UnitsP = totalUnits != 0 ? decimal.Round(brands.Skip(limit).Sum(x => x.Units) / totalUnits, 2) : 0,
                                SalesP = totalSales != 0 ? decimal.Round(brands.Skip(limit).Sum(x => x.Sales) / totalSales, 2) : 0,
                                GmP = totalGM != 0 ? decimal.Round(brands.Skip(limit).Sum(x => x.Gm) / totalGM, 2) : 0,
                                SKUsP = totalSKUs != 0 ? decimal.Round(brands.Skip(limit).Sum(x => x.SKUs) / (decimal)totalSKUs, 2) : 0,
                                SpaceP = totalSpace != 0 ? decimal.Round(brands.Skip(limit).Sum(x => x.Space) / totalSpace, 2) : 0,
                                Units = decimal.Round(brands.Skip(limit).Sum(x => x.Units), 2),
                                Sales = decimal.Round(brands.Skip(limit).Sum(x => x.Sales), 2),
                                Gm = decimal.Round(brands.Skip(limit).Sum(x => x.Gm), 2),
                                SKUs = brands.Skip(limit).Sum(x => x.SKUs),
                                Space = decimal.Round(brands.Skip(limit).Sum(x => x.Space), 2),
                            });
                    }

                    int colorCount = 0;
                    foreach (var brand in brandsAndOthers)
                    {
                        ChartSeries brandSeries = new ChartSeries(brand.Brand);
                        brandSeries.Type = ChartSeriesType.StackedBar100;
                        brandSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        brandSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        brandSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        brandSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        brandSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        brandSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem brandItem = new ChartSeriesItem();
                        brandItem.YValue = (double)brand.SalesP;
                        brandItem.Label.TextBlock.Text = (brand.SalesP * 100).ToString("N0");
                        brandItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        brandItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        brandItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        brandSeries.AddItem(brandItem);

                        //GIM
                        ChartSeriesItem brandGMItem = new ChartSeriesItem();
                        brandGMItem.YValue = (double)brand.GmP;
                        brandGMItem.Label.TextBlock.Text = (brand.GmP * 100).ToString("N0");
                        brandGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        brandGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        brandGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        brandSeries.AddItem(brandGMItem);

                        //Units
                        ChartSeriesItem brandUnitsItem = new ChartSeriesItem();
                        brandUnitsItem.YValue = (double)brand.UnitsP;
                        brandUnitsItem.Label.TextBlock.Text = (brand.UnitsP * 100).ToString("N0");
                        brandUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        brandUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        brandUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        brandSeries.AddItem(brandUnitsItem);

                        //SKUs
                        ChartSeriesItem brandSKUsItem = new ChartSeriesItem();
                        brandSKUsItem.YValue = (double)brand.SKUsP;
                        brandSKUsItem.Label.TextBlock.Text = (brand.SKUsP * 100).ToString("N0");
                        brandSKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        brandSKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        brandSKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        brandSeries.AddItem(brandSKUsItem);

                        //Space
                        if (setup.Space)
                        {
                            ChartSeriesItem brandSpaceItem = new ChartSeriesItem();
                            brandSpaceItem.YValue = (double)brand.SpaceP;
                            brandSpaceItem.Label.TextBlock.Text = (brand.SpaceP * 100).ToString("N0");
                            brandSpaceItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                            brandSpaceItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                            brandSpaceItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                            brandSeries.AddItem(brandSpaceItem);
                        }

                        chartBrand.Series.Add(brandSeries);
                    }


                    if (chartBrand.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartBrand.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartBrand.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartBrand.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartBrand.PlotArea.XAxis[3].TextBlock.Text = "% # SKUs";
                        if (setup.Space)
                        {
                            chartBrand.PlotArea.XAxis[4].TextBlock.Text = "% Space";
                        }
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartBrand.PlotArea.XAxis.Clear();
                        chartBrand.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartBrand.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartBrand.PlotArea.XAxis.AddItem("% Units");
                        chartBrand.PlotArea.XAxis.AddItem("% # SKUs");
                        if (setup.Space)
                        {
                            chartBrand.PlotArea.XAxis.AddItem("% Space");
                        }
                    }

                    iTextSharp.text.Image chartBrandImg = iTextSharp.text.Image.GetInstance(chartBrand.GetBitmap(), BaseColor.WHITE);
                    chartBrandImg.Alignment = Element.ALIGN_CENTER;
                    chartBrandImg.IndentationLeft = 10f;
                    document.Add(chartBrandImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable brandTable = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1.3f, 1.3f, 1f, 1f, 1f, 1f, 1f, 1f, 1f });
                    brandTable.WidthPercentage = 95f;

                    brandTable.AddCell(emptyCell);

                    PdfPCell subCategoryHeaderCell = new PdfPCell(new Phrase("Brand", font));
                    subCategoryHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    subCategoryHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    subCategoryHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Bottom 5%", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("# SKUs", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Volume", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Space(mt.)", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    PdfPCell subCategoryHeaderCell2 = new PdfPCell(new Phrase("AL", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    brandTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("Turns", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    brandTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("Avg. Price", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    brandTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell2 = new PdfPCell(new Phrase("% GIM", font));
                    subCategoryHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    brandTable.AddCell(subCategoryHeaderCell2);

                    subCategoryHeaderCell.Phrase = new Phrase("GMROS", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    subCategoryHeaderCell.Phrase = new Phrase("Inv Days", font);
                    brandTable.AddCell(subCategoryHeaderCell);

                    if (totalBrands > 8)
                    {
                        brandTable.AddCell(emptyCell);
                        brandTable.AddCell(emptyCell);
                        brandTable.AddCell(emptyCell);
                        brandTable.AddCell(emptyCell);
                    }

                    decimal bottomFive, skus, volume, scSales, gm, space, al, turns, averagePrice, gmPercent, gmros, invDays, inventoryCost;

                    foreach (var brand in brands)
                    {
                        bottomFive = paretoItems.Where(x => !x.IsDeletedRangeReview && x.AcumSales >= 0.95m && x.Brand.ToUpper() == brand.Brand).Count();
                        skus = brand.SKUs;
                        volume = brand.Units;
                        scSales = brand.Sales;
                        gm = brand.Gm;
                        space = brand.Space;
                        inventoryCost = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Brand.ToUpper() == brand.Brand).Sum(x => x.InventoryCost);
                        al = skus != 0 ? scSales / skus : 0;
                        turns = skus != 0 ? volume / skus : 0;
                        averagePrice = volume != 0 ? scSales / volume : 0;
                        gmPercent = scSales != 0 ? gm / scSales : 0;
                        gmros = space != 0 ? gm / space : 0;
                        invDays = (scSales - gm) != 0 ? inventoryCost / ((scSales - gm) / 30) : 0;

                        brandTable.AddCell(new PdfPCell(new Phrase(brand.Brand, font)));

                        PdfPCell cellData = new PdfPCell(new Phrase(bottomFive.ToString(), fontRed));
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(skus.ToString(), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(volume.ToString("N0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(scSales.ToString("C0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gm.ToString("C0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(space.ToString("N2"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(al.ToString("C0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(turns.ToString("N0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(averagePrice.ToString("C2"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmPercent.ToString("P1"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmros.ToString("C0"), font);
                        brandTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(invDays.ToString("N0"), font);
                        brandTable.AddCell(cellData);
                    }

                    foreach (var cell in totalTable.GetRow(0).GetCells())
                    {
                        brandTable.AddCell(cell);
                    }

                    //La tabla se banca hasta 8 filas en la misma hoja. Si no va a una hoja aparte
                    if (totalBrands > 8)
                    {
                        brandTable.HeaderRows = 6;
                        brandTable.FooterRows = 4;

                        document.NewPage();
                    }
                    else
                    {
                        brandTable.Rows.RemoveAt(0);
                    }
                    document.Add(brandTable);
                }

                #endregion

                #region Manufacturer
                if (setup.Manufacturer)
                {
                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Performance by Manufacturer";

                    document.NewPage();

                    //LG: Genero un chart de ejemplo
                    RadChart chartManufacturer = ReportsHelper.GetBarsChart("% Shares by Manufacturer");
                    chartManufacturer.Width = 750;
                    chartManufacturer.Height = 350;
                    chartManufacturer.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartManufacturer.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    //Sumarizo por Subcategoria
                    int totalManufacturers = paretoItems.Where(x => !x.IsDeletedRangeReview).Select(x => x.Manufacturer).Distinct(StringComparer.CurrentCultureIgnoreCase).Count();
                    int limit = totalManufacturers > included ? included : totalManufacturers;

                    var manufacturers = (from item in paretoItems
                                         where !item.IsDeletedRangeReview
                                         group item by item.Manufacturer.ToUpper() into g
                                         orderby g.Sum(x => x.Sales) descending
                                         select new
                                         {
                                             Manufacturer = g.Key,
                                             UnitsP = totalUnits != 0 ? g.Sum(x => x.Units) / totalUnits : 0,
                                             SalesP = totalSales != 0 ? g.Sum(x => x.Sales) / totalSales : 0,
                                             GmP = totalGM != 0 ? g.Sum(x => x.GM) / totalGM : 0,
                                             SKUsP = totalSKUs != 0 ? g.Count() / (decimal)totalSKUs : 0,
                                             SpaceP = totalSpace != 0 ? g.Sum(x => x.LinearSpace) / totalSpace : 0,
                                             Units = g.Sum(x => x.Units),
                                             Sales = g.Sum(x => x.Sales),
                                             Gm = g.Sum(x => x.GM),
                                             SKUs = g.Count(),
                                             Space = g.Sum(x => x.LinearSpace)
                                         }).ToList();

                    var manufacturersAndOthers = manufacturers.Take(limit).ToList();
                    if (totalManufacturers > included)
                    {
                        manufacturersAndOthers.Add(
                            new
                            {
                                Manufacturer = "Others",
                                UnitsP = totalUnits != 0 ? decimal.Round(manufacturers.Skip(limit).Sum(x => x.Units) / totalUnits, 2) : 0,
                                SalesP = totalSales != 0 ? decimal.Round(manufacturers.Skip(limit).Sum(x => x.Sales) / totalSales, 2) : 0,
                                GmP = totalGM != 0 ? decimal.Round(manufacturers.Skip(limit).Sum(x => x.Gm) / totalGM, 2) : 0,
                                SKUsP = totalSKUs != 0 ? decimal.Round(manufacturers.Skip(limit).Sum(x => x.SKUs) / (decimal)totalSKUs, 2) : 0,
                                SpaceP = totalSpace != 0 ? decimal.Round(manufacturers.Skip(limit).Sum(x => x.Space) / totalSpace, 2) : 0,
                                Units = decimal.Round(manufacturers.Skip(limit).Sum(x => x.Units), 2),
                                Sales = decimal.Round(manufacturers.Skip(limit).Sum(x => x.Sales), 2),
                                Gm = decimal.Round(manufacturers.Skip(limit).Sum(x => x.Gm), 2),
                                SKUs = manufacturers.Skip(limit).Sum(x => x.SKUs),
                                Space = decimal.Round(manufacturers.Skip(limit).Sum(x => x.Space), 2),
                            });
                    }

                    int colorCount = 0;
                    foreach (var manufacturer in manufacturersAndOthers)
                    {
                        ChartSeries manufacturerSeries = new ChartSeries(manufacturer.Manufacturer);
                        manufacturerSeries.Type = ChartSeriesType.StackedBar100;
                        manufacturerSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        manufacturerSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem manufacturerItem = new ChartSeriesItem();
                        manufacturerItem.YValue = (double)manufacturer.SalesP;
                        manufacturerItem.Label.TextBlock.Text = (manufacturer.SalesP * 100).ToString("N0");
                        manufacturerItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerItem);

                        //GIM
                        ChartSeriesItem manufacturerGMItem = new ChartSeriesItem();
                        manufacturerGMItem.YValue = (double)manufacturer.GmP;
                        manufacturerGMItem.Label.TextBlock.Text = (manufacturer.GmP * 100).ToString("N0");
                        manufacturerGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerGMItem);

                        //Units
                        ChartSeriesItem manufacturerUnitsItem = new ChartSeriesItem();
                        manufacturerUnitsItem.YValue = (double)manufacturer.UnitsP;
                        manufacturerUnitsItem.Label.TextBlock.Text = (manufacturer.UnitsP * 100).ToString("N0");
                        manufacturerUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerUnitsItem);

                        //SKUs
                        ChartSeriesItem manufacturerSKUsItem = new ChartSeriesItem();
                        manufacturerSKUsItem.YValue = (double)manufacturer.SKUsP;
                        manufacturerSKUsItem.Label.TextBlock.Text = (manufacturer.SKUsP * 100).ToString("N0");
                        manufacturerSKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerSKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerSKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerSKUsItem);

                        //Space
                        if (setup.Space)
                        {
                            ChartSeriesItem manufacturerSpaceItem = new ChartSeriesItem();
                            manufacturerSpaceItem.YValue = (double)manufacturer.SpaceP;
                            manufacturerSpaceItem.Label.TextBlock.Text = (manufacturer.SpaceP * 100).ToString("N0");
                            manufacturerSpaceItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                            manufacturerSpaceItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                            manufacturerSpaceItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                            manufacturerSeries.AddItem(manufacturerSpaceItem);
                        }

                        chartManufacturer.Series.Add(manufacturerSeries);
                    }

                    if (chartManufacturer.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartManufacturer.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartManufacturer.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartManufacturer.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartManufacturer.PlotArea.XAxis[3].TextBlock.Text = "% # SKUs";
                        if (setup.Space)
                        {
                            chartManufacturer.PlotArea.XAxis[4].TextBlock.Text = "% Space";
                        }
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartManufacturer.PlotArea.XAxis.Clear();
                        chartManufacturer.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartManufacturer.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartManufacturer.PlotArea.XAxis.AddItem("% Units");
                        chartManufacturer.PlotArea.XAxis.AddItem("% # SKUs");
                        if (setup.Space)
                        {
                            chartManufacturer.PlotArea.XAxis.AddItem("% Space");
                        }
                    }

                    iTextSharp.text.Image chartManufacturerImg = iTextSharp.text.Image.GetInstance(chartManufacturer.GetBitmap(), BaseColor.WHITE);
                    chartManufacturerImg.Alignment = Element.ALIGN_CENTER;
                    chartManufacturerImg.IndentationLeft = 10f;
                    document.Add(chartManufacturerImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable manufacturerTable = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1.3f, 1.3f, 1f, 1f, 1f, 1f, 1f, 1f, 1f });
                    manufacturerTable.WidthPercentage = 95f;

                    manufacturerTable.AddCell(emptyCell);

                    PdfPCell manufacturerHeaderCell = new PdfPCell(new Phrase("Manufacturer", font));
                    manufacturerHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    manufacturerHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    manufacturerHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Bottom 5%", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("# SKUs", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Volume", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Space(mt.)", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    PdfPCell manufacturerHeaderCell2 = new PdfPCell(new Phrase("AL", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("Turns", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("Avg. Price", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("% GIM", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell.Phrase = new Phrase("GMROS", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Inv Days", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    if (totalManufacturers > 8)
                    {
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                    }

                    decimal bottomFive, skus, volume, scSales, gm, space, al, turns, averagePrice, gmPercent, gmros, invDays, inventoryCost;

                    foreach (var manufacturer in manufacturers)
                    {
                        bottomFive = paretoItems.Where(x => !x.IsDeletedRangeReview && x.AcumSales >= 0.95m && x.Manufacturer.ToUpper() == manufacturer.Manufacturer).Count();
                        skus = manufacturer.SKUs;
                        volume = manufacturer.Units;
                        scSales = manufacturer.Sales;
                        gm = manufacturer.Gm;
                        space = manufacturer.Space;
                        inventoryCost = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Manufacturer.ToUpper() == manufacturer.Manufacturer).Sum(x => x.InventoryCost);
                        al = skus != 0 ? scSales / skus : 0;
                        turns = skus != 0 ? volume / skus : 0;
                        averagePrice = volume != 0 ? scSales / volume : 0;
                        gmPercent = scSales != 0 ? gm / scSales : 0;
                        gmros = space != 0 ? gm / space : 0;
                        invDays = (scSales - gm) != 0 ? inventoryCost / ((scSales - gm) / 30) : 0;

                        manufacturerTable.AddCell(new PdfPCell(new Phrase(manufacturer.Manufacturer, font)));

                        PdfPCell cellData = new PdfPCell(new Phrase(bottomFive.ToString(), fontRed));
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(skus.ToString(), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(volume.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(scSales.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gm.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(space.ToString("N2"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(al.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(turns.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(averagePrice.ToString("C2"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmPercent.ToString("P1"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmros.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(invDays.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);
                    }

                    foreach (var cell in totalTable.GetRow(0).GetCells())
                    {
                        manufacturerTable.AddCell(cell);
                    }

                    if (totalManufacturers > 8)
                    {
                        manufacturerTable.HeaderRows = 6;
                        manufacturerTable.FooterRows = 4;
                        document.NewPage();
                    }
                    else
                    {
                        manufacturerTable.Rows.RemoveAt(0);
                    }

                    document.Add(manufacturerTable);
                }
                #endregion

                #region OtherSegmentations
                foreach (var segmentation in RangeReviewSetupAttributesRepository.Select(x => x.RangeReviewSetupId == setup.Id))
                {
                    var segment = AttributeTypesRepository.Select(x => x.Id == segmentation.AttributeTypeId).FirstOrDefault();
                    var paretoItemsSegmentRows = ReportsRepository.GetSalesCategoryComparisonPareto(rangeReviewId, categoryId, false, segmentation.AttributeTypeId, 1).Where(x => !x.IsDeletedRangeReview).ToList();
                    List<SalesCategoryComparisonPareto> paretoItemsSegment = paretoItemsSegmentRows.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

                    //Completo el nuevo Pareto
                    decimal acumSalesS = 0;
                    foreach (var item in paretoItemsSegment.OrderByDescending(x => x.Sales))
                    {
                        acumSalesS += item.Sales;
                        item.AcumSales = totalSales != 0 ? acumSalesS / totalSales : 0;
                    }

                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Performance by " + segment.Name;

                    document.NewPage();

                    //LG: Genero un chart de ejemplo
                    RadChart chartManufacturer = ReportsHelper.GetBarsChart("% Shares by " + segment.Name);
                    chartManufacturer.Width = 750;
                    chartManufacturer.Height = 350;
                    chartManufacturer.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartManufacturer.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    //Sumarizo por Subcategoria
                    int totalSegment = paretoItemsSegment.Select(x => x.Segment).Distinct().Count();
                    int limit = totalSegment > included ? included : totalSegment;

                    var segments = (from item in paretoItemsSegment
                                    group item by item.Segment into g
                                    orderby g.Sum(x => x.Sales) descending
                                    select new
                                    {
                                        Segment = g.Key,
                                        UnitsP = totalUnits != 0 ? g.Sum(x => x.Units) / totalUnits : 0,
                                        SalesP = totalSales != 0 ? g.Sum(x => x.Sales) / totalSales : 0,
                                        GmP = totalGM != 0 ? g.Sum(x => x.GM) / totalGM : 0,
                                        SKUsP = totalSKUs != 0 ? g.Count() / (decimal)totalSKUs : 0,
                                        SpaceP = totalSpace != 0 ? g.Sum(x => x.LinearSpace) / totalSpace : 0,
                                        Units = g.Sum(x => x.Units),
                                        Sales = g.Sum(x => x.Sales),
                                        Gm = g.Sum(x => x.GM),
                                        SKUs = g.Count(),
                                        Space = g.Sum(x => x.LinearSpace)
                                    }).ToList();

                    var segmentsAndOthers = segments.Take(limit).ToList();
                    if (totalSegment > included)
                    {
                        segmentsAndOthers.Add(
                            new
                            {
                                Segment = "Others",
                                UnitsP = totalUnits != 0 ? decimal.Round(segments.Skip(limit).Sum(x => x.Units) / totalUnits, 2) : 0,
                                SalesP = totalSales != 0 ? decimal.Round(segments.Skip(limit).Sum(x => x.Sales) / totalSales, 2) : 0,
                                GmP = totalGM != 0 ? decimal.Round(segments.Skip(limit).Sum(x => x.Gm) / totalGM, 2) : 0,
                                SKUsP = totalSKUs != 0 ? decimal.Round(segments.Skip(limit).Sum(x => x.SKUs) / (decimal)totalSKUs, 2) : 0,
                                SpaceP = totalSpace != 0 ? decimal.Round(segments.Skip(limit).Sum(x => x.Space) / totalSpace, 2) : 0,
                                Units = decimal.Round(segments.Skip(limit).Sum(x => x.Units), 2),
                                Sales = decimal.Round(segments.Skip(limit).Sum(x => x.Sales), 2),
                                Gm = decimal.Round(segments.Skip(limit).Sum(x => x.Gm), 2),
                                SKUs = segments.Skip(limit).Sum(x => x.SKUs),
                                Space = decimal.Round(segments.Skip(limit).Sum(x => x.Space), 2),
                            });
                    }

                    int colorCount = 0;
                    foreach (var item in segmentsAndOthers)
                    {
                        ChartSeries manufacturerSeries = new ChartSeries(item.Segment);
                        manufacturerSeries.Type = ChartSeriesType.StackedBar100;
                        manufacturerSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        manufacturerSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        manufacturerSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem manufacturerItem = new ChartSeriesItem();
                        manufacturerItem.YValue = (double)item.SalesP;
                        manufacturerItem.Label.TextBlock.Text = (item.SalesP * 100).ToString("N0");
                        manufacturerItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerItem);

                        //GIM
                        ChartSeriesItem manufacturerGMItem = new ChartSeriesItem();
                        manufacturerGMItem.YValue = (double)item.GmP;
                        manufacturerGMItem.Label.TextBlock.Text = (item.GmP * 100).ToString("N0");
                        manufacturerGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerGMItem);

                        //Units
                        ChartSeriesItem manufacturerUnitsItem = new ChartSeriesItem();
                        manufacturerUnitsItem.YValue = (double)item.UnitsP;
                        manufacturerUnitsItem.Label.TextBlock.Text = (item.UnitsP * 100).ToString("N0");
                        manufacturerUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerUnitsItem);

                        //SKUs
                        ChartSeriesItem manufacturerSKUsItem = new ChartSeriesItem();
                        manufacturerSKUsItem.YValue = (double)item.SKUsP;
                        manufacturerSKUsItem.Label.TextBlock.Text = (item.SKUsP * 100).ToString("N0");
                        manufacturerSKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        manufacturerSKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        manufacturerSKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        manufacturerSeries.AddItem(manufacturerSKUsItem);

                        //Space
                        if (setup.Space)
                        {
                            ChartSeriesItem manufacturerSpaceItem = new ChartSeriesItem();
                            manufacturerSpaceItem.YValue = (double)item.SpaceP;
                            manufacturerSpaceItem.Label.TextBlock.Text = (item.SpaceP * 100).ToString("N0");
                            manufacturerSpaceItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                            manufacturerSpaceItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                            manufacturerSpaceItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                            manufacturerSeries.AddItem(manufacturerSpaceItem);
                        }

                        chartManufacturer.Series.Add(manufacturerSeries);
                    }

                    if (chartManufacturer.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartManufacturer.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartManufacturer.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartManufacturer.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartManufacturer.PlotArea.XAxis[3].TextBlock.Text = "% # SKUs";
                        if (setup.Space)
                        {
                            chartManufacturer.PlotArea.XAxis[4].TextBlock.Text = "% Space";
                        }
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartManufacturer.PlotArea.XAxis.Clear();
                        chartManufacturer.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartManufacturer.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartManufacturer.PlotArea.XAxis.AddItem("% Units");
                        chartManufacturer.PlotArea.XAxis.AddItem("% # SKUs");
                        if (setup.Space)
                        {
                            chartManufacturer.PlotArea.XAxis.AddItem("% Space");
                        }
                    }

                    iTextSharp.text.Image chartManufacturerImg = iTextSharp.text.Image.GetInstance(chartManufacturer.GetBitmap(), BaseColor.WHITE);
                    chartManufacturerImg.Alignment = Element.ALIGN_CENTER;
                    chartManufacturerImg.IndentationLeft = 10f;
                    document.Add(chartManufacturerImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable manufacturerTable = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1.3f, 1.3f, 1f, 1f, 1f, 1f, 1f, 1f, 1f });
                    manufacturerTable.WidthPercentage = 95f;

                    manufacturerTable.AddCell(emptyCell);

                    PdfPCell manufacturerHeaderCell = new PdfPCell(new Phrase(segment.Name, font));
                    manufacturerHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    manufacturerHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    manufacturerHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Bottom 5%", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("# SKUs", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Volume", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Space(mt.)", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    PdfPCell manufacturerHeaderCell2 = new PdfPCell(new Phrase("AL", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("Turns", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("Avg. Price", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell2 = new PdfPCell(new Phrase("% GIM", font));
                    manufacturerHeaderCell2.BackgroundColor = new BaseColor(222, 247, 247);
                    manufacturerTable.AddCell(manufacturerHeaderCell2);

                    manufacturerHeaderCell.Phrase = new Phrase("GMROS", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    manufacturerHeaderCell.Phrase = new Phrase("Inv Days", font);
                    manufacturerTable.AddCell(manufacturerHeaderCell);

                    if (totalSegment > 8)
                    {
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                        manufacturerTable.AddCell(emptyCell);
                    }

                    decimal bottomFive, skus, volume, scSales, gm, space, al, turns, averagePrice, gmPercent, gmros, invDays, inventoryCost;

                    foreach (var item in segments)
                    {
                        bottomFive = paretoItemsSegment.Where(x => x.AcumSales >= 0.95m && x.Segment == item.Segment).Count();
                        skus = item.SKUs;
                        volume = item.Units;
                        scSales = item.Sales;
                        gm = item.Gm;
                        space = item.Space;
                        inventoryCost = paretoItemsSegment.Where(x => x.Segment == item.Segment).Sum(x => x.InventoryCost);
                        al = skus != 0 ? scSales / skus : 0;
                        turns = skus != 0 ? volume / skus : 0;
                        averagePrice = volume != 0 ? scSales / volume : 0;
                        gmPercent = scSales != 0 ? gm / scSales : 0;
                        gmros = space != 0 ? gm / space : 0;
                        invDays = (scSales - gm) != 0 ? inventoryCost / ((scSales - gm) / 30) : 0;

                        manufacturerTable.AddCell(new PdfPCell(new Phrase(item.Segment, font)));

                        PdfPCell cellData = new PdfPCell(new Phrase(bottomFive.ToString(), fontRed));
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(skus.ToString(), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(volume.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(scSales.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gm.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(space.ToString("N2"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(al.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(turns.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(averagePrice.ToString("C2"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmPercent.ToString("P1"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmros.ToString("C0"), font);
                        manufacturerTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(invDays.ToString("N0"), font);
                        manufacturerTable.AddCell(cellData);
                    }

                    foreach (var cell in totalTable.GetRow(0).GetCells())
                    {
                        manufacturerTable.AddCell(cell);
                    }

                    if (totalSegment > 8)
                    {
                        manufacturerTable.HeaderRows = 6;
                        manufacturerTable.FooterRows = 4;
                        document.NewPage();
                    }
                    else
                    {
                        manufacturerTable.Rows.RemoveAt(0);
                    }

                    document.Add(manufacturerTable);
                }

                #endregion

                #region Combos
                if (setup.Combos)
                {
                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Type of product: Single / Combo";

                    document.NewPage();

                    RadChart chartCombos = ReportsHelper.GetBarsChart("% Shares by Type of Product");
                    chartCombos.Width = 750;
                    chartCombos.Height = 350;
                    chartCombos.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartCombos.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    var combos = ReportsRepository.GetCategorySameStoreComparisonCombos(rangeReview.Id, categoryId, 1);

                    int colorCount = 0;
                    int comboTotalSKUs = combos.Sum(x => x.SKUs) - 1 + totalSKUs;
                    foreach (var combo in combos.OrderByDescending(x => x.Sales))
                    {
                        ChartSeries combosSeries = new ChartSeries(combo.Title);
                        combosSeries.Type = ChartSeriesType.StackedBar100;
                        combosSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        combosSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        combosSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        combosSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        combosSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        combosSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem comboItem = new ChartSeriesItem();
                        comboItem.YValue = (double)combo.Sales / (double)totalSales;
                        comboItem.Label.TextBlock.Text = (combo.Sales / totalSales * 100).ToString("N0");
                        comboItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        comboItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        comboItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        combosSeries.AddItem(comboItem);

                        //GIM
                        ChartSeriesItem comboGMItem = new ChartSeriesItem();
                        comboGMItem.YValue = (double)combo.GM / (double)totalGM;
                        comboGMItem.Label.TextBlock.Text = (combo.GM / totalGM * 100).ToString("N0");
                        comboGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        comboGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        comboGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        combosSeries.AddItem(comboGMItem);

                        //Units
                        ChartSeriesItem comboUnitsItem = new ChartSeriesItem();
                        comboUnitsItem.YValue = (double)combo.Units / (double)totalUnits;
                        comboUnitsItem.Label.TextBlock.Text = (combo.Units / totalUnits * 100).ToString("N0");
                        comboUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        comboUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        comboUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        combosSeries.AddItem(comboUnitsItem);

                        //SKUs
                        ChartSeriesItem comboSKUsItem = new ChartSeriesItem();
                        comboSKUsItem.YValue = combo.Title == "Single" ? (double)totalSKUs / comboTotalSKUs : (double)combo.SKUs / comboTotalSKUs;
                        comboSKUsItem.Label.TextBlock.Text = combo.Title == "Single" ? ((decimal)totalSKUs / comboTotalSKUs * 100).ToString("N0") : ((decimal)combo.SKUs / comboTotalSKUs * 100).ToString("N0");
                        comboSKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        comboSKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        comboSKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        combosSeries.AddItem(comboSKUsItem);

                        chartCombos.Series.Add(combosSeries);

                    }

                    if (chartCombos.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartCombos.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartCombos.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartCombos.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartCombos.PlotArea.XAxis[3].TextBlock.Text = "% #";
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartCombos.PlotArea.XAxis.Clear();
                        chartCombos.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartCombos.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartCombos.PlotArea.XAxis.AddItem("% Units");
                        chartCombos.PlotArea.XAxis.AddItem("% #");
                    }

                    iTextSharp.text.Image chartCombosImg = iTextSharp.text.Image.GetInstance(chartCombos.GetBitmap(), BaseColor.WHITE);
                    chartCombosImg.Alignment = Element.ALIGN_CENTER;
                    chartCombosImg.IndentationLeft = 10f;
                    document.Add(chartCombosImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable comboTable = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1f, 1f, 1f });
                    comboTable.WidthPercentage = 80f;
                    comboTable.SpacingBefore = 20f;

                    PdfPCell comboHeaderCell = new PdfPCell(new Phrase("Type of Product", font));
                    comboHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    comboHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    comboHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell.Phrase = new Phrase("#", font);
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell.Phrase = new Phrase("Volume", font);
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell = new PdfPCell(new Phrase("Avg. Price", font));
                    comboHeaderCell.BackgroundColor = new BaseColor(222, 247, 247);
                    comboTable.AddCell(comboHeaderCell);

                    comboHeaderCell = new PdfPCell(new Phrase("% GIM", font));
                    comboHeaderCell.BackgroundColor = new BaseColor(222, 247, 247);
                    comboTable.AddCell(comboHeaderCell);

                    foreach (var combo in combos.OrderByDescending(x => x.Sales))
                    {
                        PdfPCell cellData = new PdfPCell();
                        cellData.HorizontalAlignment = Element.ALIGN_LEFT;
                        cellData.Phrase = new Phrase(combo.Title, font);
                        comboTable.AddCell(cellData);

                        if (combo.Title == "Single")
                        {
                            cellData.Phrase = new Phrase(totalSKUs.ToString("N0"), font);
                        }
                        else
                        {
                            cellData.Phrase = new Phrase(combo.SKUs.ToString("N0"), font);
                        }
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        comboTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(combo.Units.ToString("N0"), font);
                        comboTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(combo.Sales.ToString("C0"), font);
                        comboTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(combo.GM.ToString("C0"), font);
                        comboTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(combo.Units != 0 ? (combo.Sales / combo.Units).ToString("C2") : string.Empty, font);
                        comboTable.AddCell(cellData);

                        cellData.Phrase = new Phrase(combo.Sales != 0 ? (combo.GM / combo.Sales).ToString("P1") : string.Empty, font);
                        comboTable.AddCell(cellData);
                    }

                    //Totales
                    totalCellData.Phrase = new Phrase(string.Empty);
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(comboTotalSKUs.ToString("N0"), font);
                    totalCellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalUnits.ToString("N0"), font);
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalSales.ToString("C0"), font);
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalGM.ToString("C0"), font);
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase((combos.Sum(x => x.Sales) / combos.Sum(x => x.Units)).ToString("C2"), font);
                    comboTable.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase((combos.Sum(x => x.GM) / combos.Sum(x => x.Sales)).ToString("P1"), font);
                    comboTable.AddCell(totalCellData);

                    document.Add(comboTable);

                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    Paragraph p = new Paragraph("Note: In Combos each item is allocated in their respective subcategory . E.g. Sandwich + French Fries + Beverage. Each of them should be found on its respective subcategory/category).", font);
                    p.IndentationLeft = 60f;
                    document.Add(p);
                }
                #endregion

                #endregion

                #region Exhibition Space Analysis
                if (setup.SpaceAnalysis)
                {
                    ((PageEvent)writer.PageEvent).Title = string.Empty;
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                    document.NewPage();

                    Paragraph caratulaSpace = new Paragraph();
                    caratulaSpace.SpacingBefore = 180f;
                    caratulaSpace.IndentationLeft = 100f;
                    caratulaSpace.IndentationRight = 20f;
                    caratulaSpace.Add(new Phrase("Exhibition Space Analysis", font30));
                    document.Add(caratulaSpace);

                    document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));

                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    document.Add(new Paragraph(" "));
                    Paragraph p = new Paragraph("Note: Sales allocation for articles exhibited in more than one Planogram, is calculated according to the number of facings present in each Planogram.", font);
                    p.IndentationLeft = 60f;
                    document.Add(p);

                    ((PageEvent)writer.PageEvent).Title = "Exhibition Space Analysis";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Allocation Shares";

                    document.NewPage();

                    RadChart chartSpaces = ReportsHelper.GetBarsChart("% Shares by Space Allocation");
                    chartSpaces.Width = 750;
                    chartSpaces.Height = 350;
                    chartSpaces.SeriesOrientation = ChartSeriesOrientation.Horizontal;
                    chartSpaces.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                    //Sumarizo por Location
                    var spaceRows = ReportsRepository.GetSalesCategoryComparisonBySpace(rangeReview.Id, categoryId, false, 1).Where(x => !x.IsDeletedRangeReview && x.LinearSpace > 0);
                    decimal totalLocationUnits = spaceRows.Sum(x => x.Units);
                    decimal totalLocationSales = spaceRows.Sum(x => x.Sales);
                    decimal totalLocationSpace = spaceRows.Sum(x => x.LinearSpace) / 100m;
                    decimal totalLocationGM = spaceRows.Sum(x => x.GM);
                    decimal totalLocationInventory = spaceRows.Sum(x => x.InventoryCost);
                    int totalLocationSKUs = spaceRows.Count();

                    var locations = (from item in spaceRows
                                     group item by item.Location1 into g
                                     orderby g.Sum(x => x.Sales) descending
                                     select new
                                     {
                                         Location = g.Key,
                                         Units = g.Sum(x => x.Units),
                                         Sales = g.Sum(x => x.Sales),
                                         Gm = g.Sum(x => x.GM),
                                         SKUs = g.Count(),
                                         Space = g.Sum(x => x.LinearSpace),
                                         InventoryCost = g.Sum(x => x.InventoryCost),
                                         UnitsP = totalLocationUnits != 0 ? g.Sum(x => x.Units) / totalLocationUnits : 0,
                                         SalesP = totalLocationSales != 0 ? g.Sum(x => x.Sales) / totalLocationSales : 0,
                                         SKUsP = totalLocationSKUs != 0 ? g.Count() / (decimal)totalLocationSKUs : 0,
                                         SpaceP = totalLocationSpace != 0 ? (g.Sum(x => x.LinearSpace) / 100m) / totalLocationSpace : 0,
                                         GmP = totalLocationGM != 0 ? g.Sum(x => x.GM) / totalLocationGM : 0
                                     }).ToList();

                    int totalLocations = locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase).Count();

                    int colorCount = 0;
                    foreach (var item in locations)
                    {
                        ChartSeries locationSeries = new ChartSeries(item.Location);
                        locationSeries.Type = ChartSeriesType.StackedBar100;
                        locationSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                        locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                        locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                        locationSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                        locationSeries.Appearance.Border.Visible = false;

                        colorCount++;

                        //Sales
                        ChartSeriesItem locationItem = new ChartSeriesItem();
                        locationItem.YValue = (double)item.SalesP;
                        locationItem.Label.TextBlock.Text = (item.SalesP * 100).ToString("N0");
                        locationItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        locationItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        locationItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        locationItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                        locationSeries.AddItem(locationItem);

                        //GIM
                        ChartSeriesItem locationGMItem = new ChartSeriesItem();
                        locationGMItem.YValue = (double)item.GmP;
                        locationGMItem.Label.TextBlock.Text = (item.GmP * 100).ToString("N0");
                        locationGMItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        locationGMItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        locationGMItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        locationGMItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                        locationSeries.AddItem(locationGMItem);

                        //Units
                        ChartSeriesItem locationUnitsItem = new ChartSeriesItem();
                        locationUnitsItem.YValue = (double)item.UnitsP;
                        locationUnitsItem.Label.TextBlock.Text = (item.UnitsP * 100).ToString("N0");
                        locationUnitsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        locationUnitsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        locationUnitsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        locationUnitsItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                        locationSeries.AddItem(locationUnitsItem);

                        //SKUs
                        ChartSeriesItem locationSKUsItem = new ChartSeriesItem();
                        locationSKUsItem.YValue = (double)item.SKUsP;
                        locationSKUsItem.Label.TextBlock.Text = (item.SKUsP * 100).ToString("N0");
                        locationSKUsItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        locationSKUsItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        locationSKUsItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        locationSKUsItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                        locationSeries.AddItem(locationSKUsItem);

                        //Space
                        ChartSeriesItem locationSpaceItem = new ChartSeriesItem();
                        locationSpaceItem.YValue = (double)item.SpaceP;
                        locationSpaceItem.Label.TextBlock.Text = (item.SpaceP * 100).ToString("N0");
                        locationSpaceItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        locationSpaceItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        locationSpaceItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                        locationSpaceItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                        locationSeries.AddItem(locationSpaceItem);

                        chartSpaces.Series.Add(locationSeries);
                    }

                    if (chartSpaces.PlotArea.XAxis.Items.Count >= 3)
                    {
                        // JUST CHANGING THE LABES OF THE X AXIS.
                        chartSpaces.PlotArea.XAxis[0].TextBlock.Text = "% Sales " + currencySymbol;
                        chartSpaces.PlotArea.XAxis[1].TextBlock.Text = "% GIM " + currencySymbol;
                        chartSpaces.PlotArea.XAxis[2].TextBlock.Text = "% Units";
                        chartSpaces.PlotArea.XAxis[3].TextBlock.Text = "% # SKUs";
                        chartSpaces.PlotArea.XAxis[4].TextBlock.Text = "% Space";
                    }
                    else
                    {
                        // ADDING NEW ELEMENTS TO THE X AXIS.
                        chartSpaces.PlotArea.XAxis.Clear();
                        chartSpaces.PlotArea.XAxis.AddItem("% Sales " + currencySymbol);
                        chartSpaces.PlotArea.XAxis.AddItem("% GIM " + currencySymbol);
                        chartSpaces.PlotArea.XAxis.AddItem("% Units");
                        chartSpaces.PlotArea.XAxis.AddItem("% # SKUs");
                        chartSpaces.PlotArea.XAxis.AddItem("% Space");
                    }

                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartSpaces.GetBitmap(), BaseColor.WHITE);
                    chartImg.Alignment = 1;
                    chartImg.IndentationLeft = 10f;
                    document.Add(chartImg);

                    //Tabla con datos
                    //Genero una tabla con datos
                    PdfPTable spacesTableDetails = new PdfPTable(new float[] { 3f, 1f, 1f, 1f, 1f, 1f, 1f, 1f });
                    spacesTableDetails.WidthPercentage = 90f;
                    spacesTableDetails.HeaderRows = 1;

                    PdfPCell spacesHeaderCell = new PdfPCell(new Phrase("Allocation", font));
                    spacesHeaderCell.BackgroundColor = new BaseColor(184, 204, 228);
                    spacesHeaderCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    spacesHeaderCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("# SKUs", font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("Volume", font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("GIM " + currencySymbol, font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("Space(mt.)", font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("GMROS", font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    spacesHeaderCell.Phrase = new Phrase("Inv Days", font);
                    spacesTableDetails.AddCell(spacesHeaderCell);

                    decimal skus, volume, scSales, gm, space, gmros, invDays, inventoryCost;

                    foreach (var item in locations)
                    {
                        skus = item.SKUs;
                        volume = item.Units;
                        scSales = item.Sales;
                        gm = item.Gm;
                        space = item.Space / 100m; //Lo paso a metros lineales
                        gmros = space != 0 ? gm / space : 0;
                        inventoryCost = item.InventoryCost;
                        invDays = (scSales - gm) != 0 ? inventoryCost / ((scSales - gm) / 30) : 0;

                        spacesTableDetails.AddCell(new PdfPCell(new Phrase(item.Location, font)));

                        PdfPCell cellData = new PdfPCell(new Phrase(skus.ToString(), font));
                        cellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(volume.ToString("N0"), font);
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(scSales.ToString("C0"), font);
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(gm.ToString("C0"), font);
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(space.ToString("N2"), font);
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(gmros.ToString("C0"), font);
                        spacesTableDetails.AddCell(cellData);

                        cellData.Phrase = new Phrase(invDays.ToString("N0"), font);
                        spacesTableDetails.AddCell(cellData);
                    }

                    totalCellData = new PdfPCell(new Phrase(""));
                    totalCellData.BackgroundColor = new BaseColor(184, 204, 228);
                    totalCellData.HorizontalAlignment = Element.ALIGN_RIGHT;
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalLocationSKUs.ToString("N0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalLocationUnits.ToString("N0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalLocationSales.ToString("C0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalLocationGM.ToString("C0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase(totalLocationSpace.ToString("N2"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    totalCellData.Phrase = new Phrase((totalLocationSpace != 0 ? totalLocationGM / totalLocationSpace : 0).ToString("C0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    decimal totalLocationInvDays = (totalLocationSales - totalLocationGM) != 0 ? totalLocationInventory / ((totalLocationSales - totalLocationGM) / 30) : 0;
                    totalCellData.Phrase = new Phrase(totalLocationInvDays.ToString("N0"), font);
                    spacesTableDetails.AddCell(totalCellData);

                    //La tabla se banca hasta 8 filas en la misma hoja. Si no va a una hoja aparte
                    emptyCell.Colspan = 8;
                    if (totalLocations > 8)
                    {
                        spacesTableDetails.HeaderRows = 4;
                        spacesTableDetails.FooterRows = 3;
                        spacesTableDetails.SpacingBefore = 20f;
                        spacesTableDetails.AddCell(emptyCell);
                        spacesTableDetails.AddCell(emptyCell);
                        spacesTableDetails.AddCell(emptyCell);

                        document.NewPage();
                    }
                    document.Add(spacesTableDetails);

                    if (setup.SpaceBrand)
                    {
                        ((PageEvent)writer.PageEvent).Title = "Exhibition Space Analysis";
                        ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Allocation by Brand";

                        document.NewPage();

                        RadChart chartBrand1Spaces = ReportsHelper.GetBarsChart("Brand Space by Location");
                        chartBrand1Spaces.Legend.Visible = false;
                        chartBrand1Spaces.Width = 500;
                        chartBrand1Spaces.Height = 350;
                        chartBrand1Spaces.SeriesOrientation = ChartSeriesOrientation.Vertical;
                        chartBrand1Spaces.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;

                        RadChart chartBrand2Spaces = ReportsHelper.GetBarsChart("Brand Sales by Location");
                        chartBrand2Spaces.Legend.Visible = true;
                        chartBrand2Spaces.Width = 600;
                        chartBrand2Spaces.Height = 350;
                        chartBrand2Spaces.SeriesOrientation = ChartSeriesOrientation.Vertical;
                        chartBrand2Spaces.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.False;
                        chartBrand2Spaces.Legend.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Right;
                        chartBrand2Spaces.Legend.Appearance.Overflow = Telerik.Charting.Styles.Overflow.Column;

                        //Sumarizo por Marca y Location
                        included = 7;
                        int totalBrands = spaceRows.Select(x => x.Brand).Distinct(StringComparer.CurrentCultureIgnoreCase).Count();
                        int limit = totalBrands > included ? included : totalBrands;

                        var limitBrand = from item in spaceRows
                                         group item by item.Brand into g
                                         orderby g.Sum(x => x.Sales) descending
                                         select new { Brand = g.Key, Sales = g.Sum(x => x.Sales) };

                        limitBrand = limitBrand.Take(limit);

                        var locationsByBrand = (from item in spaceRows
                                                group item by new { item.Location1, Brand = limitBrand.Any(x => x.Brand == item.Brand) ? item.Brand.ToUpper() : "Others" } into g
                                                orderby g.Sum(x => x.Sales) descending
                                                select new
                                                {
                                                    Location = g.Key.Location1,
                                                    Brand = g.Key.Brand.ToUpper(),
                                                    Units = g.Sum(x => x.Units),
                                                    Sales = g.Sum(x => x.Sales),
                                                    Gm = g.Sum(x => x.GM),
                                                    SKUs = g.Count(),
                                                    Space = g.Sum(x => x.LinearSpace),
                                                    InventoryCost = g.Sum(x => x.InventoryCost),
                                                }).ToList();

                        colorCount = 0;

                        foreach (var brand in locationsByBrand.Select(x => x.Brand).Distinct(StringComparer.CurrentCultureIgnoreCase))
                        {
                            ChartSeries locationSeries = new ChartSeries(brand);
                            locationSeries.Type = ChartSeriesType.StackedBar100;
                            locationSeries.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                            locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                            locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                            locationSeries.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                            locationSeries.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                            locationSeries.Appearance.Border.Visible = false;

                            ChartSeries locationSeries2 = new ChartSeries(brand);
                            locationSeries2.Type = ChartSeriesType.StackedBar100;
                            locationSeries2.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                            locationSeries2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 0f));
                            locationSeries2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount + 16], 0.5f));
                            locationSeries2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[colorCount], 1f));
                            locationSeries2.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Vertical;
                            locationSeries2.Appearance.Border.Visible = false;

                            colorCount++;

                            foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                            {
                                var item = locationsByBrand.Where(x => x.Location == location && x.Brand == brand).FirstOrDefault();
                                if (item != null)
                                {
                                    ChartSeriesItem locationItem = new ChartSeriesItem();
                                    decimal totalSpaceByItem = locationsByBrand.Where(x => x.Location == location).Sum(x => x.Space);
                                    decimal spaceP = totalSpaceByItem != 0m ? item.Space / totalSpaceByItem : 0m;
                                    locationItem.YValue = (double)spaceP;
                                    locationItem.Label.TextBlock.Text = (spaceP * 100).ToString("N0");
                                    locationItem.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                                    locationItem.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                                    locationItem.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                                    locationItem.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                                    locationSeries.AddItem(locationItem);

                                    ChartSeriesItem locationItem2 = new ChartSeriesItem();
                                    decimal totalSalesByItem = locationsByBrand.Where(x => x.Location == location).Sum(x => x.Sales);
                                    decimal salesP = totalSalesByItem != 0m ? item.Sales / totalSalesByItem : 0m;
                                    locationItem2.YValue = (double)salesP;
                                    locationItem2.Label.TextBlock.Text = (salesP * 100).ToString("N0");
                                    locationItem2.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                                    locationItem2.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                                    locationItem2.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                                    locationItem2.Label.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7f, System.Drawing.FontStyle.Regular);
                                    locationSeries2.AddItem(locationItem2);
                                }
                                else
                                {
                                    ChartSeriesItem locationItem = new ChartSeriesItem();
                                    locationItem.YValue = 0d;
                                    locationItem.Label.Visible = false;
                                    locationSeries.AddItem(locationItem);
                                    locationSeries2.AddItem(locationItem);
                                }
                            }

                            chartBrand1Spaces.Series.Add(locationSeries);
                            chartBrand2Spaces.Series.Add(locationSeries2);
                        }

                        foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                        {
                            chartBrand1Spaces.PlotArea.XAxis.AddItem(location);
                            chartBrand2Spaces.PlotArea.XAxis.AddItem(location);
                        }

                        iTextSharp.text.Image chartBrand1SpacesImg = iTextSharp.text.Image.GetInstance(chartBrand1Spaces.GetBitmap(), BaseColor.WHITE);
                        chartBrand1SpacesImg.Alignment = Element.ALIGN_LEFT;

                        iTextSharp.text.Image chartBrand2SpacesImg = iTextSharp.text.Image.GetInstance(chartBrand2Spaces.GetBitmap(), BaseColor.WHITE);
                        chartBrand2SpacesImg.Alignment = Element.ALIGN_LEFT;

                        PdfPTable chartBrandTable = new PdfPTable(new float[] { 45f, 55f });
                        chartBrandTable.WidthPercentage = 95f;
                        PdfPCell chartBrandCell = new PdfPCell();
                        chartBrandCell.BorderWidth = 0;
                        chartBrandCell.VerticalAlignment = Element.ALIGN_BOTTOM;
                        chartBrandCell.Image = chartBrand1SpacesImg;
                        chartBrandTable.AddCell(chartBrandCell);
                        chartBrandCell.Image = chartBrand2SpacesImg;
                        chartBrandTable.AddCell(chartBrandCell);
                        document.Add(chartBrandTable);

                        int totalCells = ((totalLocations + 2) * 2) + 1;
                        float[] totalCellsWitdth = new float[totalCells];
                        for (int i = 0; i < totalCellsWitdth.Length; i++)
                        {
                            if (i == 0 || i == totalLocations + 3)
                            {
                                totalCellsWitdth.SetValue(2f, i);
                            }
                            else
                            {
                                totalCellsWitdth.SetValue(1f, i);
                            }
                        }
                        PdfPTable chartBrandTableDetails = new PdfPTable(totalCellsWitdth);
                        chartBrandTableDetails.WidthPercentage = 95f;
                        chartBrandTableDetails.SpacingBefore = 10f;

                        emptyCell.Colspan = totalCells;
                        chartBrandTableDetails.AddCell(emptyCell);

                        PdfPCell headerCell = new PdfPCell(new Phrase("Brand (Space)", font));
                        headerCell.BackgroundColor = new BaseColor(184, 204, 228);
                        headerCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        headerCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        chartBrandTableDetails.AddCell(headerCell);

                        foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                        {
                            headerCell.Phrase = new Phrase(location, font);
                            chartBrandTableDetails.AddCell(headerCell);
                        }

                        headerCell.Phrase = new Phrase("Total", font);
                        chartBrandTableDetails.AddCell(headerCell);

                        PdfPCell blankCell = new PdfPCell();
                        blankCell.BorderWidth = 0f;
                        chartBrandTableDetails.AddCell(blankCell);

                        headerCell.Phrase = new Phrase("Brand (Sales)", font);
                        chartBrandTableDetails.AddCell(headerCell);

                        foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                        {
                            headerCell.Phrase = new Phrase(location, font);
                            chartBrandTableDetails.AddCell(headerCell);
                        }

                        headerCell.Phrase = new Phrase("Total", font);
                        chartBrandTableDetails.AddCell(headerCell);

                        if (totalBrands > 12)
                        {
                            chartBrandTableDetails.AddCell(emptyCell);
                            chartBrandTableDetails.AddCell(emptyCell);
                            chartBrandTableDetails.AddCell(emptyCell);
                        }

                        var locationsByBrand2 = (from item in spaceRows
                                                 group item by new { item.Location1, Brand = item.Brand } into g
                                                 orderby g.Sum(x => x.Sales) descending
                                                 select new
                                                 {
                                                     Location = g.Key.Location1,
                                                     Brand = g.Key.Brand.ToUpper(),
                                                     Units = g.Sum(x => x.Units),
                                                     Sales = g.Sum(x => x.Sales),
                                                     Gm = g.Sum(x => x.GM),
                                                     SKUs = g.Count(),
                                                     Space = g.Sum(x => x.LinearSpace),
                                                     InventoryCost = g.Sum(x => x.InventoryCost),
                                                 }).ToList();

                        PdfPCell cellData = new PdfPCell();
                        var brands = (from s in spaceRows group s by s.Brand.ToUpper() into g orderby g.Sum(x => x.Sales) descending select g.Key);
                        foreach (var brand in brands)
                        {
                            cellData.HorizontalAlignment = Element.ALIGN_LEFT;

                            cellData.Phrase = new Phrase(brand, font);
                            chartBrandTableDetails.AddCell(cellData);

                            cellData.HorizontalAlignment = Element.ALIGN_RIGHT;

                            decimal totalSpace2 = 0;
                            foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                            {
                                var item = locationsByBrand2.Where(x => x.Location == location && x.Brand == brand).FirstOrDefault();
                                if (item != null)
                                {
                                    totalSpace2 += item.Space;
                                    cellData.Phrase = new Phrase((item.Space / 100m).ToString("N2"), font);
                                    chartBrandTableDetails.AddCell(cellData);
                                }
                                else
                                {
                                    cellData.Phrase = new Phrase(" ");
                                    chartBrandTableDetails.AddCell(cellData);
                                }
                            }

                            cellData.Phrase = new Phrase((totalSpace2 / 100m).ToString("N2"), font);
                            chartBrandTableDetails.AddCell(cellData);

                            chartBrandTableDetails.AddCell(blankCell);

                            cellData.HorizontalAlignment = Element.ALIGN_LEFT;

                            cellData.Phrase = new Phrase(brand, font);
                            chartBrandTableDetails.AddCell(cellData);

                            cellData.HorizontalAlignment = Element.ALIGN_RIGHT;

                            decimal totalSales2 = 0;
                            foreach (var location in locations.Select(x => x.Location).Distinct(StringComparer.CurrentCultureIgnoreCase))
                            {
                                var item = locationsByBrand2.Where(x => x.Location == location && x.Brand == brand).FirstOrDefault();
                                if (item != null)
                                {
                                    totalSales2 += item.Sales;
                                    cellData.Phrase = new Phrase(item.Sales.ToString("C0"), font);
                                    chartBrandTableDetails.AddCell(cellData);
                                }
                                else
                                {
                                    cellData.Phrase = new Phrase(" ");
                                    chartBrandTableDetails.AddCell(cellData);
                                }
                            }

                            cellData.Phrase = new Phrase(totalSales2.ToString("C0"), font);
                            chartBrandTableDetails.AddCell(cellData);
                        }

                        if (totalBrands > 12)
                        {
                            chartBrandTableDetails.HeaderRows = 5;
                            chartBrandTableDetails.FooterRows = 3;
                        }

                        document.Add(chartBrandTableDetails);
                    }

                }
                #endregion

                #region AnalysisConclusions

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                Paragraph caratula2 = new Paragraph();
                caratula2.SpacingBefore = 180f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.Add(new Phrase("Analysis Conclusions", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Replacement Product Proposal

                ((PageEvent)writer.PageEvent).Title = "Analysis Conclusions";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Replacement Product Proposal";

                document.NewPage();

                //Replacement Product Proposal
                PdfPTable replacementTable = new PdfPTable(5);
                replacementTable.HorizontalAlignment = Element.ALIGN_CENTER;
                replacementTable.WidthPercentage = 85f;
                replacementTable.SetWidths(new float[] { 32f, 17f, 17f, 17f, 17f });
                replacementTable.SpacingBefore = 20f;

                emptyCell.Colspan = 1;

                PdfPCell replacementheaderCell1 = new PdfPCell(new Phrase("REPLACEMENT PROPOSAL", font10blue));
                replacementheaderCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementheaderCell1.Padding = 4f;
                replacementheaderCell1.BorderColor = new BaseColor(197, 217, 241);
                replacementheaderCell1.BorderWidthLeft = 1;
                replacementheaderCell1.BorderWidthRight = 0;
                replacementheaderCell1.BorderWidthTop = 1;
                replacementheaderCell1.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementheaderCell1);
                PdfPCell replacementheaderCell2 = new PdfPCell(new Phrase("# SKUs", font10blue));
                replacementheaderCell2.Padding = 4f;
                replacementheaderCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementheaderCell2.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementheaderCell2.BorderColor = new BaseColor(197, 217, 241);
                replacementheaderCell2.BorderWidthLeft = 0;
                replacementheaderCell2.BorderWidthRight = 0;
                replacementheaderCell2.BorderWidthTop = 1;
                replacementheaderCell2.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementheaderCell2);
                PdfPCell replacementheaderCell3 = new PdfPCell(new Phrase("% SKUs", font10blue));
                replacementheaderCell3.Padding = 4f;
                replacementheaderCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementheaderCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementheaderCell3.BorderColor = new BaseColor(197, 217, 241);
                replacementheaderCell3.BorderWidthLeft = 0;
                replacementheaderCell3.BorderWidthRight = 0;
                replacementheaderCell3.BorderWidthTop = 1;
                replacementheaderCell3.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementheaderCell3);
                PdfPCell replacementheaderCell4 = new PdfPCell(new Phrase("SALES", font10blue));
                replacementheaderCell4.Padding = 4f;
                replacementheaderCell4.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementheaderCell4.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementheaderCell4.BorderColor = new BaseColor(197, 217, 241);
                replacementheaderCell4.BorderWidthLeft = 0;
                replacementheaderCell4.BorderWidthRight = 0;
                replacementheaderCell4.BorderWidthTop = 1;
                replacementheaderCell4.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementheaderCell4);
                PdfPCell replacementheaderCell5 = new PdfPCell(new Phrase("% SALES", font10blue));
                replacementheaderCell5.Padding = 4f;
                replacementheaderCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementheaderCell5.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementheaderCell5.BorderColor = new BaseColor(197, 217, 241);
                replacementheaderCell5.BorderWidthLeft = 0;
                replacementheaderCell5.BorderWidthRight = 1;
                replacementheaderCell5.BorderWidthTop = 1;
                replacementheaderCell5.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementheaderCell5);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);

                int delistedSKUs = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Delist).Count();
                int activeSKUs = totalSKUs - delistedSKUs;
                decimal delistedSKUsP = totalSKUs != 0 ? delistedSKUs / (decimal)totalSKUs : 0;
                decimal activeSKUsP = totalSKUs != 0 ? activeSKUs / (decimal)totalSKUs : 0;
                decimal delistedSales = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Delist).Sum(x => x.Sales);
                decimal activeSales = totalSales - delistedSales;
                decimal delistedSalesP = totalSales != 0 ? delistedSales / totalSales : 0;
                decimal activeSalesP = totalSales != 0 ? activeSales / totalSales : 0;
                decimal delistedSpace = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Delist).Sum(x => x.LinearSpace);
                decimal activeSpace = totalSpace - delistedSpace;
                decimal delistedSpaceP = totalSpace != 0 ? delistedSpace / totalSpace : 0;
                decimal activeSpaceP = totalSpace != 0 ? activeSpace / totalSpace : 0;
                decimal delistedInventory = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Delist).Sum(x => x.InventoryCost);
                decimal activeInventory = totalInventory - delistedInventory;
                decimal delistedInventoryP = totalInventory != 0 ? delistedInventory / totalInventory : 0;
                decimal activeInventoryP = totalInventory != 0 ? activeInventory / totalInventory : 0;

                PdfPCell replacementCell11 = new PdfPCell(new Phrase("In", font10));
                replacementCell11.BorderWidth = 0;
                replacementCell11.BackgroundColor = new BaseColor(197, 217, 241);
                replacementCell11.Padding = 4f;
                replacementCell11.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementTable.AddCell(replacementCell11);

                PdfPCell replacementCell12 = new PdfPCell(new Phrase(activeSKUs.ToString(), font10));
                replacementCell12.BorderWidth = 0;
                replacementCell12.BackgroundColor = new BaseColor(197, 217, 241);
                replacementCell12.Padding = 4f;
                replacementCell12.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell12.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell12);

                PdfPCell replacementCell13 = new PdfPCell(new Phrase(activeSKUsP.ToString("P0"), font10));
                replacementCell13.BorderWidth = 0;
                replacementCell13.BackgroundColor = new BaseColor(197, 217, 241);
                replacementCell13.Padding = 4f;
                replacementCell13.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell13.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell13);

                PdfPCell replacementCell14 = new PdfPCell(new Phrase(activeSales.ToString("C0"), font10));
                replacementCell14.BorderWidth = 0;
                replacementCell14.BackgroundColor = new BaseColor(197, 217, 241);
                replacementCell14.Padding = 4f;
                replacementCell14.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell14.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell14);

                PdfPCell replacementCell15 = new PdfPCell(new Phrase(activeSalesP.ToString("P0"), font10));
                replacementCell15.BorderWidth = 0;
                replacementCell15.BackgroundColor = new BaseColor(197, 217, 241);
                replacementCell15.Padding = 4f;
                replacementCell15.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell15.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell15);

                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);

                PdfPCell replacementCell21 = new PdfPCell(new Phrase("Out", font10));
                replacementCell21.BorderWidth = 0;
                replacementCell21.BackgroundColor = new BaseColor(80, 210, 210);
                replacementCell21.Padding = 4f;
                replacementCell21.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementTable.AddCell(replacementCell21);

                PdfPCell replacementCell22 = new PdfPCell(new Phrase(delistedSKUs.ToString(), font10));
                replacementCell22.BorderWidth = 0;
                replacementCell22.BackgroundColor = new BaseColor(80, 210, 210);
                replacementCell22.Padding = 4f;
                replacementCell22.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell22.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell22);

                PdfPCell replacementCell23 = new PdfPCell(new Phrase(delistedSKUsP.ToString("P0"), font10));
                replacementCell23.BorderWidth = 0;
                replacementCell23.BackgroundColor = new BaseColor(80, 210, 210);
                replacementCell23.Padding = 4f;
                replacementCell23.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell23.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell23);

                PdfPCell replacementCell24 = new PdfPCell(new Phrase(delistedSales.ToString("C0"), font10));
                replacementCell24.BorderWidth = 0;
                replacementCell24.BackgroundColor = new BaseColor(80, 210, 210);
                replacementCell24.Padding = 4f;
                replacementCell24.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell24.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell24);

                PdfPCell replacementCell25 = new PdfPCell(new Phrase(delistedSalesP.ToString("P0"), font10));
                replacementCell25.BorderWidth = 0;
                replacementCell25.BackgroundColor = new BaseColor(80, 210, 210);
                replacementCell25.Padding = 4f;
                replacementCell25.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell25.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementTable.AddCell(replacementCell25);

                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);
                replacementTable.AddCell(emptyCell);

                PdfPCell replacementCell31 = new PdfPCell(new Phrase("TOTAL ANALYZED", font10blue));
                replacementCell31.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell31.Padding = 4f;
                replacementCell31.BorderColor = new BaseColor(197, 217, 241);
                replacementCell31.BorderWidthLeft = 1;
                replacementCell31.BorderWidthRight = 0;
                replacementCell31.BorderWidthTop = 1;
                replacementCell31.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementCell31);
                PdfPCell replacementCell32 = new PdfPCell(new Phrase(totalSKUs.ToString(), font10blue));
                replacementCell32.Padding = 4f;
                replacementCell32.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell32.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementCell32.BorderColor = new BaseColor(197, 217, 241);
                replacementCell32.BorderWidthLeft = 0;
                replacementCell32.BorderWidthRight = 0;
                replacementCell32.BorderWidthTop = 1;
                replacementCell32.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementCell32);
                PdfPCell replacementCell33 = new PdfPCell(new Phrase("100 %", font10blue));
                replacementCell33.Padding = 4f;
                replacementCell33.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell33.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementCell33.BorderColor = new BaseColor(197, 217, 241);
                replacementCell33.BorderWidthLeft = 0;
                replacementCell33.BorderWidthRight = 0;
                replacementCell33.BorderWidthTop = 1;
                replacementCell33.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementCell33);
                PdfPCell replacementCell34 = new PdfPCell(new Phrase(totalSales.ToString("C0"), font10blue));
                replacementCell34.Padding = 4f;
                replacementCell34.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell34.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementCell34.BorderColor = new BaseColor(197, 217, 241);
                replacementCell34.BorderWidthLeft = 0;
                replacementCell34.BorderWidthRight = 0;
                replacementCell34.BorderWidthTop = 1;
                replacementCell34.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementCell34);
                PdfPCell replacementCell35 = new PdfPCell(new Phrase("100 %", font10blue));
                replacementCell35.Padding = 4f;
                replacementCell35.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementCell35.HorizontalAlignment = Element.ALIGN_RIGHT;
                replacementCell35.BorderColor = new BaseColor(197, 217, 241);
                replacementCell35.BorderWidthLeft = 0;
                replacementCell35.BorderWidthRight = 1;
                replacementCell35.BorderWidthTop = 1;
                replacementCell35.BorderWidthBottom = 1;
                replacementTable.AddCell(replacementCell35);

                document.Add(replacementTable);

                int repTableColumn = 1;
                if (setup.Space)
                {
                    replacementTable.Rows[0].GetCells().ElementAt(1).Phrase = new Phrase("SPACE", font10blue);
                    replacementTable.Rows[0].GetCells().ElementAt(2).Phrase = new Phrase("% SPACE", font10blue);
                    replacementTable.Rows[2].GetCells().ElementAt(1).Phrase = new Phrase(activeSpace.ToString("N1") + " mt.", font10);
                    replacementTable.Rows[2].GetCells().ElementAt(2).Phrase = new Phrase(activeSpaceP.ToString("P0"), font10);
                    replacementTable.Rows[4].GetCells().ElementAt(1).Phrase = new Phrase(delistedSpace.ToString("N1") + " mt.", font10);
                    replacementTable.Rows[4].GetCells().ElementAt(2).Phrase = new Phrase(delistedSpaceP.ToString("P0"), font10);
                    replacementTable.Rows[6].GetCells().ElementAt(1).Phrase = new Phrase(totalSpace.ToString("N1") + " mt.", font10);
                    replacementTable.Rows[6].GetCells().ElementAt(2).Phrase = new Phrase("100 %", font10);
                    repTableColumn = repTableColumn + 2;
                }
                
                if (setup.Inventory)
                {
                    replacementTable.Rows[0].GetCells().ElementAt(repTableColumn).Phrase = new Phrase("INVENTORY", font10blue);
                    replacementTable.Rows[0].GetCells().ElementAt(repTableColumn + 1).Phrase = new Phrase("% INVENTORY", font10blue);

                    replacementTable.Rows[2].GetCells().ElementAt(repTableColumn).Phrase = new Phrase(activeInventory.ToString("C0"), font10);
                    replacementTable.Rows[2].GetCells().ElementAt(repTableColumn + 1).Phrase = new Phrase(activeInventoryP.ToString("P0"), font10);

                    replacementTable.Rows[4].GetCells().ElementAt(repTableColumn).Phrase = new Phrase(delistedInventory.ToString("C0"), font10);
                    replacementTable.Rows[4].GetCells().ElementAt(repTableColumn + 1).Phrase = new Phrase(delistedInventoryP.ToString("P0"), font10);

                    replacementTable.Rows[6].GetCells().ElementAt(repTableColumn).Phrase = new Phrase(totalInventory.ToString("C0"), font10);
                    replacementTable.Rows[6].GetCells().ElementAt(repTableColumn + 1).Phrase = new Phrase("100 %", font10);

                }

                if ((setup.Inventory && !setup.Space) || (!setup.Inventory && setup.Space))
                {
                    replacementTable.Rows[0].GetCells().ElementAt(3).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[0].GetCells().ElementAt(4).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[2].GetCells().ElementAt(3).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[2].GetCells().ElementAt(4).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[4].GetCells().ElementAt(3).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[4].GetCells().ElementAt(4).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[6].GetCells().ElementAt(3).Phrase = new Phrase(string.Empty);
                    replacementTable.Rows[6].GetCells().ElementAt(4).Phrase = new Phrase(string.Empty);
                }

                if (setup.Inventory || setup.Space)
                {
                    document.Add(replacementTable);
                }

                repTableColumn = 0;
                if (setup.Space)
                {
                    repTableColumn = 2;
                }
                if (setup.Inventory)
                {
                    repTableColumn += 2;
                }
                repTableColumn += 5;

                PdfPTable replacementSubcategoryTable = new PdfPTable(repTableColumn);
                replacementSubcategoryTable.HorizontalAlignment = Element.ALIGN_CENTER;
                replacementSubcategoryTable.WidthPercentage = 85f;
                float[] replacementSubcategoryTableWidths = new float[repTableColumn];
                for (int i = 0; i < repTableColumn; i++)
                {
                    if (i == 0)
                    {
                        replacementSubcategoryTableWidths.SetValue(20f, i);
                    }
                    else
                    {
                        replacementSubcategoryTableWidths.SetValue(10f, i);
                    }
                }
                replacementSubcategoryTable.SetWidths(replacementSubcategoryTableWidths);
                replacementSubcategoryTable.SpacingBefore = 10f;
                replacementSubcategoryTable.HeaderRows = 5;
                replacementSubcategoryTable.FooterRows = 2;
                int prevColspan = emptyTableCell.Colspan;
                emptyTableCell.Colspan = repTableColumn;

                replacementSubcategoryTable.AddCell(emptyTableCell);

                PdfPCell replacementSubcategoryCell11 = new PdfPCell(new Phrase("Replacement Products", font10));
                replacementSubcategoryCell11.Padding = 4f;
                replacementSubcategoryCell11.VerticalAlignment = Element.ALIGN_MIDDLE;
                replacementSubcategoryCell11.HorizontalAlignment = Element.ALIGN_CENTER;
                replacementSubcategoryCell11.BackgroundColor = new BaseColor(80, 210, 210);
                replacementSubcategoryCell11.BorderWidth = 0;
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(string.Empty, font10);
                replacementSubcategoryCell11.Colspan = 2;
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(string.Empty, font10);
                replacementSubcategoryCell11.Colspan = 2;
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                if (setup.Space)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase(string.Empty, font10);
                    replacementSubcategoryCell11.Colspan = 2;
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                if (setup.Inventory)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase(string.Empty, font10);
                    replacementSubcategoryCell11.Colspan = 2;
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                replacementSubcategoryCell11.Colspan = 1;

                replacementSubcategoryCell11.Phrase = new Phrase("Proposal per Subcategory", font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.HorizontalAlignment = Element.ALIGN_RIGHT;

                replacementSubcategoryCell11.Phrase = new Phrase("# SKUs", font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase("% SKUs", font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase("SALES", font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase("% SALES", font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                if (setup.Space)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase("SPACE", font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    replacementSubcategoryCell11.Phrase = new Phrase("% SPACE", font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                if (setup.Inventory)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase("INVENTORY", font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    replacementSubcategoryCell11.Phrase = new Phrase("% INVENTORY", font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                replacementSubcategoryTable.AddCell(emptyTableCell);
                replacementSubcategoryTable.AddCell(emptyTableCell);

                emptyTableCell.Colspan = prevColspan;

                
                foreach (var subcategory in paretoItems.Where(x => !x.IsDeletedRangeReview).Select(x => x.Subcategory).Distinct())
                {
                    replacementSubcategoryCell11.BackgroundColor = BaseColor.WHITE;
                    replacementSubcategoryCell11.HorizontalAlignment = Element.ALIGN_CENTER;

                    replacementSubcategoryCell11.Phrase = new Phrase(subcategory, font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    replacementSubcategoryCell11.HorizontalAlignment = Element.ALIGN_RIGHT;

                    int subDelistedSKUs = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory && x.Delist).Count();
                    replacementSubcategoryCell11.Phrase = new Phrase(subDelistedSKUs.ToString(), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    int subSKUs = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory).Count();
                    decimal result = subSKUs != 0 ? subDelistedSKUs / (decimal)subSKUs : 0;
                    replacementSubcategoryCell11.Phrase = new Phrase(result.ToString("P0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    decimal subDelistedSales = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory && x.Delist).Sum(x => x.Sales);
                    replacementSubcategoryCell11.Phrase = new Phrase(subDelistedSales.ToString("C0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    decimal subSales = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory).Sum(x => x.Sales);
                    result = subSales != 0 ? (subDelistedSales / subSales) : 0;
                    replacementSubcategoryCell11.Phrase = new Phrase(result.ToString("P0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    if (setup.Space)
                    {
                        decimal subDelistedSpace = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory && x.Delist).Sum(x => x.LinearSpace);
                        replacementSubcategoryCell11.Phrase = new Phrase(subDelistedSpace.ToString("N1") + " mt.", font10);
                        replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                        decimal subSpace = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory).Sum(x => x.LinearSpace);
                        result = subSpace != 0 ? (subDelistedSpace / subSpace) : 0;
                        replacementSubcategoryCell11.Phrase = new Phrase(result.ToString("P0"), font10);
                        replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                    }

                    if (setup.Inventory)
                    {
                        decimal subDelistedInventory = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory && x.Delist).Sum(x => x.InventoryCost);
                        replacementSubcategoryCell11.Phrase = new Phrase(subDelistedInventory.ToString("C0"), font10);
                        replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                        decimal subInventory = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Subcategory == subcategory).Sum(x => x.InventoryCost);
                        result = subInventory != 0 ? (subDelistedInventory / subInventory) : 0;
                        replacementSubcategoryCell11.Phrase = new Phrase(result.ToString("P0"), font10);
                        replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                    }
                }

                replacementSubcategoryCell11.BackgroundColor = new BaseColor(80, 210, 210);
                replacementSubcategoryCell11.Phrase = new Phrase(string.Empty);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(delistedSKUs.ToString(), font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(delistedSKUsP.ToString("P0"), font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(delistedSales.ToString("C0"), font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                replacementSubcategoryCell11.Phrase = new Phrase(delistedSalesP.ToString("P0"), font10);
                replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                if (setup.Space)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase(delistedSpace.ToString("N1") + " mt.", font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    replacementSubcategoryCell11.Phrase = new Phrase(delistedSpaceP.ToString("P0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                if (setup.Inventory)
                {
                    replacementSubcategoryCell11.Phrase = new Phrase(delistedInventory.ToString("C0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);

                    replacementSubcategoryCell11.Phrase = new Phrase(delistedInventoryP.ToString("P0"), font10);
                    replacementSubcategoryTable.AddCell(replacementSubcategoryCell11);
                }

                document.Add(replacementSubcategoryTable);
                #endregion

                #region Replacement Product Proposal - Poor Performing SKUs
                //Replacement Proposal - Poor Performing SKUs
                ((PageEvent)writer.PageEvent).Title = "Analysis Conclusions";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Replacement Product Proposal - \"Watch list\"";

                document.NewPage();

                //Replacement Product Proposal
                PdfPTable poorPerfSkusTable = new PdfPTable(new float[] { 8f, 20f, 6f, 6f, 6f, 6f });
                poorPerfSkusTable.WidthPercentage = 75;
                poorPerfSkusTable.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                poorPerfSkusTable.HeaderRows = 6;
                poorPerfSkusTable.FooterRows = 3;
                emptyCell.Colspan = 6;


                poorPerfSkusTable.AddCell(emptyCell);

                PdfPCell poorHeaderCell = new PdfPCell(new Phrase("Identify Poor Performing SKUs", font10));
                poorHeaderCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                poorHeaderCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                poorHeaderCell.Padding = 4f;
                poorHeaderCell.BackgroundColor = new BaseColor(154, 154, 255);
                poorHeaderCell.BorderWidthLeft = 1;
                poorHeaderCell.BorderWidthRight = 1;
                poorHeaderCell.BorderWidthTop = 1;
                poorHeaderCell.BorderWidthBottom = 1;
                poorHeaderCell.BorderColor = BaseColor.WHITE;


                poorHeaderCell.Phrase = new Phrase("Identify Poor Performing SKUs", font10);
                poorHeaderCell.Colspan = 6;
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorHeaderCell.Phrase = new Phrase("Article Nº", font10);
                poorHeaderCell.Colspan = 1;
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorHeaderCell.Phrase = new Phrase("Description", font10);
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorHeaderCell.Phrase = new Phrase("Volume", font10);
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorHeaderCell.Phrase = new Phrase("Sales " + currencySymbol, font10);
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorHeaderCell.Phrase = new Phrase("Recommendation", font10);
                poorHeaderCell.Colspan = 2;
                poorPerfSkusTable.AddCell(poorHeaderCell);

                poorPerfSkusTable.AddCell(emptyCell);
                poorPerfSkusTable.AddCell(emptyCell);
                poorPerfSkusTable.AddCell(emptyCell);


                PdfPCell poorDataCell = new PdfPCell();
                poorDataCell.Padding = 4f;
                poorDataCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                poorDataCell.BackgroundColor = new BaseColor(204, 204, 255);
                poorDataCell.BorderWidthLeft = 1;
                poorDataCell.BorderWidthRight = 1;
                poorDataCell.BorderWidthTop = 1;
                poorDataCell.BorderWidthBottom = 1;
                poorDataCell.BorderColor = BaseColor.WHITE;


                int refNum = 1;
                string refDesc = null;
                Dictionary<int, string> recommendations = new Dictionary<int, string>();
                List<Recommendation> recomm = new List<Recommendation>();

                foreach (var paretoItem in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
                {
                    if (paretoItem.AcumSales >= (1 - (rangeReview.Bottom / 100)) || paretoItem.Delist)
                    {
                        Font lineFont = new Font(Calibri, 9, Font.NORMAL);

                        if (!string.IsNullOrWhiteSpace(paretoItem.DelistComment))
                        {
                            refDesc = "ref. #" + refNum;

                            recomm.Add(new Recommendation
                                {
                                    refNum = refNum++,
                                    Comment = paretoItem.DelistComment,
                                    lineFont = paretoItem.Delist ? new Font(Calibri, 9, Font.NORMAL, BaseColor.RED) : new Font(Calibri, 9, Font.NORMAL, BaseColor.BLACK)
                                });
                        }
                        else
                        {
                            refDesc = null;
                        }

                        if (paretoItem.Delist)
                            lineFont.Color = BaseColor.RED;
                        else
                            lineFont.Color = BaseColor.BLACK;

                        poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        poorDataCell.Phrase = new Phrase(paretoItem.Code, lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);

                        poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        poorDataCell.Phrase = new Phrase(paretoItem.Name, lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);

                        poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        poorDataCell.Phrase = new Phrase(paretoItem.Units.ToString("N0"), lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);

                        poorDataCell.Phrase = new Phrase(paretoItem.Sales.ToString("C0"), lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);

                        poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        poorDataCell.Phrase = new Phrase(refDesc, lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);

                        poorDataCell.Phrase = new Phrase(paretoItem.Delist ? "Out" : "In", lineFont);
                        poorPerfSkusTable.AddCell(poorDataCell);
                    }
                }

                poorDataCell.Phrase = new Phrase(" ");
                poorDataCell.Colspan = 6;
                poorPerfSkusTable.AddCell(poorDataCell);

                foreach (var rec in recomm.OrderBy(x => x.refNum))
                {
                    poorDataCell.Phrase = new Phrase(string.Format("ref. #{0} - {1}", rec.refNum, rec.Comment), rec.lineFont);
                    poorDataCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    poorDataCell.Colspan = 6;
                    poorPerfSkusTable.AddCell(poorDataCell);
                }

                document.Add(poorPerfSkusTable);
                #endregion

                #region SKUs with sales not present in Article Master (Ninth Lock)

                var ninthLockData = paretoItems.Where(x => x.IsDelisted && x.Sales > 0);

                if (ninthLockData.Any())
                {
                    ((PageEvent)writer.PageEvent).Title = "Analysis Conclusions";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "SKUs with sales not present in Article Master";
                    document.NewPage();

                    PdfPTable ninthLockTable = new PdfPTable(new float[] { 1, 3, 9, 2, 6, 2, 4, 4, 2 });
                    ninthLockTable.WidthPercentage = 90;
                    ninthLockTable.HeaderRows = 7;
                    ninthLockTable.FooterRows = 3;
                    emptyTableCell.Colspan = 9;
                    ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                    ninthLockTable.AddCell(emptyTableCell);
                    emptyTableCell.BackgroundColor = new BaseColor(204, 204, 255);
                    emptyTableCell.Phrase = new Phrase("These SKUs are not listed in the model store and were not included in the range performance analysis. Please validate the sales performance where listed and consider their de-listing.", font10);
                    ninthLockTable.AddCell(emptyTableCell);
                    emptyTableCell.BackgroundColor = BaseColor.WHITE;
                    emptyTableCell.Phrase = new Phrase(" ");
                    ninthLockTable.AddCell(emptyTableCell);

                    ninthLockTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                    ninthLockTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;

                    ninthLockTable.AddCell(new Phrase("#", font10));
                    ninthLockTable.AddCell(new Phrase("Article Nº", font10));
                    ninthLockTable.AddCell(new Phrase("Description", font10));
                    ninthLockTable.AddCell(new Phrase("MC", font10));
                    ninthLockTable.AddCell(new Phrase("Subcategory", font10));
                    ninthLockTable.AddCell(new Phrase("Volume", font10));
                    ninthLockTable.AddCell(new Phrase("Sales " + currencySymbol, font10));
                    ninthLockTable.AddCell(new Phrase("GI Margin " + currencySymbol, font10));
                    ninthLockTable.AddCell(new Phrase("# Stores", font10));

                    ninthLockTable.AddCell(emptyTableCell);
                    ninthLockTable.AddCell(emptyTableCell);
                    ninthLockTable.AddCell(emptyTableCell);

                    ninthLockTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                    int rank = 1;
                    foreach (var item in ninthLockData.OrderByDescending(x => x.Sales))
                    {
                        ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        ninthLockTable.AddCell(new Phrase(rank++.ToString("N0"), font10));
                        ninthLockTable.AddCell(new Phrase(item.Code, font10));
                        ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        ninthLockTable.AddCell(new Phrase(item.Name, font10));
                        ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        ninthLockTable.AddCell(new Phrase(item.MC, font10));
                        ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        ninthLockTable.AddCell(new Phrase(item.Subcategory, font10));
                        ninthLockTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        ninthLockTable.AddCell(new Phrase(item.Units.ToString("N0"), font10));
                        ninthLockTable.AddCell(new Phrase(item.Sales.ToString("C2"), font10));
                        ninthLockTable.AddCell(new Phrase(item.GM.ToString("C2"), font10));
                        ninthLockTable.AddCell(new Phrase(item.StoreCoverageQuantity.ToString("N0"), font10));
                    }

                    ninthLockTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                    ninthLockTable.AddCell("");
                    ninthLockTable.AddCell("");
                    ninthLockTable.AddCell("");
                    ninthLockTable.AddCell("");
                    ninthLockTable.AddCell("");
                    ninthLockTable.AddCell(new Phrase(ninthLockData.Sum(x => x.Units).ToString("N0"), font10));
                    ninthLockTable.AddCell(new Phrase(ninthLockData.Sum(x => x.Sales).ToString("C0"), font10));
                    ninthLockTable.AddCell(new Phrase(ninthLockData.Sum(x => x.GM).ToString("C0"), font10));
                    ninthLockTable.AddCell("");

                    document.Add(ninthLockTable);
                }
                #endregion

                #endregion

                #region Appendix

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                caratula2 = new Paragraph();
                caratula2.SpacingBefore = 180f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.Add(new Phrase("APPENDIX", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Pareto

                //List<int> rrStores = RangeReviewDomain.GetRangeReviewStores(rangeReview).Where(x => x.IsSelected).Select(x => x.StoreId).ToList();
                //decimal coverage = rrStores.Count * rangeReview.TotalMonths;

                //var salesByDateRows = ReportsRepository.GetSalesCategoryComparisonByDate(rangeReview.Id, category.Id);

                /*
                var salesBySkuType = from item in salesByDateRows
                                     group item by new { item.Id, item.Code, item.Name, item.Brand, item.Category, item.Subcategory } into g
                                     select new
                                     {
                                         ArticleId = g.Key.Id,
                                         Code = g.Key.Code,
                                         Name = g.Key.Name,
                                         Brand = g.Key.Brand,
                                         Category = g.Key.Category,
                                         Subcategory = g.Key.Subcategory,
                                         Units = g.Sum(x => x.Units) / coverage,
                                         UnitsCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Units) / coverage,
                                         UnitsPY = g.Where(x => x.IsPriorYear).Sum(x => x.Units) / coverage,
                                         Sales = g.Sum(x => x.Sales) / coverage,
                                         SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) / coverage,
                                         SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales) / coverage,
                                         Margin = g.Sum(x => x.GM) / coverage,
                                         MarginCY = g.Where(x => !x.IsPriorYear).Sum(x => x.GM) / coverage,
                                         MarginPY = g.Where(x => x.IsPriorYear).Sum(x => x.GM) / coverage,
                                         Status = (g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0) ? SKUStatus.Active :
                                                   g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) == 0 ? SKUStatus.New :
                                                   g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) == 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0 ? SKUStatus.Delisted : SKUStatus.None
                                     };
                 */

                ((PageEvent)writer.PageEvent).Title = "Appendix";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Pareto Sales " + currencySymbol;

                document.NewPage();

                PdfPTable paretoTable = new PdfPTable(12);
                paretoTable.SetWidths(new float[] { 4f, 8f, 20f, 5f, 14f, 5f, 8f, 8f, 4f, 5f, 4f, 4f });
                paretoTable.WidthPercentage = 95f;
                //paretoTable.TotalWidth = document.PageSize.Width - 10f;
                paretoTable.SplitLate = true;
                paretoTable.SplitRows = true;
                paretoTable.HeaderRows = 4; //4 filas en total, solo 2 son del header
                paretoTable.FooterRows = 2; // porque 2 las toma el footer. 
                emptyCell.Colspan = 12;


                //HEADER
                PdfPCell legendsCell = new PdfPCell();
                legendsCell.Colspan = 12;
                legendsCell.BorderWidth = 0;
                PdfPTable legendsTable = new PdfPTable(5);
                legendsTable.SetWidths(new float[] { 5f, 20f, 5f, 20f, 50f });
                legendsTable.WidthPercentage = 30f;
                PdfPCell legend1Cell = new PdfPCell();
                legend1Cell.BorderColorBottom = BaseColor.BLUE;
                legend1Cell.BorderWidth = 0;
                legend1Cell.Padding = 5f;
                legend1Cell.BorderWidthBottom = 1;
                legendsTable.AddCell(legend1Cell);
                legend1Cell.Phrase = new Phrase("Average Line", font10);
                legend1Cell.BorderWidthBottom = 0;
                legendsTable.AddCell(legend1Cell);
                legend1Cell.BorderColorBottom = BaseColor.RED;
                legend1Cell.BorderWidthBottom = 1;
                legend1Cell.Phrase = new Phrase(string.Empty);
                legendsTable.AddCell(legend1Cell);
                legend1Cell.Phrase = new Phrase("Bottom 5 %", font10);
                legend1Cell.BorderWidthBottom = 0;
                legendsTable.AddCell(legend1Cell);

                //Si tuvo ventas mayores a 0 este año y no estaba el año pasado
                if (paretoItems.Any(x => !x.IsDeletedRangeReview && x.Sales > 0m && !paretoItemsWithPY.Where(p => p.IsPriorYear && p.Sales > 0m).Any(p => p.Id == x.Id)))
                {
                    legend1Cell.Phrase = new Phrase("Note: Items marked in yellow are classified as New", font10);
                }
                else
                {
                    legend1Cell.Phrase = new Phrase(" ", font10);
                }
                legendsTable.AddCell(legend1Cell);
                legendsCell.Table = legendsTable;
                paretoTable.AddCell(legendsCell);

                PdfPCell paretoTableCell1 = new PdfPCell(new Phrase("#", font9));
                paretoTableCell1.Padding = 4f;
                paretoTableCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                paretoTableCell1.HorizontalAlignment = Element.ALIGN_CENTER;
                paretoTableCell1.BackgroundColor = new BaseColor(80, 210, 210);
                paretoTableCell1.BorderWidth = 0.5f;
                paretoTableCell1.BorderColor = BaseColor.LIGHT_GRAY;
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Article N°", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Description", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("MC", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Subcategory", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Volume", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Sales " + currencySymbol, font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("GI Margin " + currencySymbol, font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("% GIM", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("Sales Contrib.", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("% Acum Sales", font9);
                paretoTable.AddCell(paretoTableCell1);

                paretoTableCell1.Phrase = new Phrase("% Acum SKUs", font9);
                paretoTable.AddCell(paretoTableCell1);

                //2 filas en blanco para el footer.
                paretoTable.AddCell(emptyCell);
                paretoTable.AddCell(emptyCell);

                paretoTableCell1.BackgroundColor = BaseColor.WHITE;

                int number = 0;
                acumSales = 0;
                emptyCell.Colspan = 12;
                bool averageLineDraw = false;
                bool bottom5LineDraw = false;
                paretoTableCell1.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
                {
                    number++;
                    item.Ranking = number;
                    item.PrevAcumSales = acumSales / totalSales;
                    acumSales += item.Sales;
                    item.AcumSales = acumSales / totalSales;
                    item.AcumSKUs = number / (decimal)totalSKUs;

                    //Busco si ese item no tuvo ventas el año anterior entonces asumo que es nuevo
                    if (item.Sales > 0m && !paretoItemsWithPY.Any(x => x.Id == item.Id && x.IsPriorYear && x.Sales > 0m))
                    {
                        paretoTableCell1.BackgroundColor = new BaseColor(255, 255, 204);
                    }
                    else
                    {
                        paretoTableCell1.BackgroundColor = BaseColor.WHITE;
                    }

                    if (!averageLineDraw && item.Sales < averageLine)
                    {
                        paretoTableCell1.BorderWidthTop = 2;
                        paretoTableCell1.BorderColorTop = BaseColor.BLUE;
                        averageLineDraw = true;
                    }
                    else
                    {
                        if (!bottom5LineDraw && item.AcumSales >= 0.95m)
                        {
                            paretoTableCell1.BorderWidthTop = 2;
                            paretoTableCell1.BorderColorTop = BaseColor.RED;
                            bottom5LineDraw = true;
                        }
                        else
                        {
                            paretoTableCell1.BorderWidthTop = 0.5f;
                            paretoTableCell1.BorderColorTop = BaseColor.LIGHT_GRAY;
                        }
                    }

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    paretoTableCell1.Phrase = new Phrase(number.ToString(), font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    paretoTableCell1.Phrase = new Phrase(item.Code, font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    paretoTableCell1.Phrase = new Phrase(item.Name, font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    paretoTableCell1.Phrase = new Phrase(item.MC, font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    paretoTableCell1.Phrase = new Phrase(item.Subcategory, font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    paretoTableCell1.Phrase = new Phrase(item.Units.ToString("N0"), font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.Phrase = new Phrase(item.Sales.ToString("C2"), font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.Phrase = new Phrase(item.GM.ToString("C2"), font9);
                    paretoTable.AddCell(paretoTableCell1);

                    //TODO DB: Pinchaba aqui por division x cero. Validar que hacer aca. Por el momento si no puedo hacer la division le paso un string vacio, como para que deje de pinchar.
                    paretoTableCell1.Phrase = item.Sales != 0 ? new Phrase((item.GM / item.Sales).ToString("P0"), font9) : new Phrase("");
                    paretoTable.AddCell(paretoTableCell1);

                    //TODO DB: Pinchaba aqui por division x cero. Validar que hacer aca. Por el momento si no puedo hacer la division le paso un string vacio, como para que deje de pinchar.
                    paretoTableCell1.Phrase = totalSales != 0 ? new Phrase((item.Sales / totalSales).ToString("P0"), font9) : new Phrase("");
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.Phrase = new Phrase(item.AcumSales.ToString("P0"), font9);
                    paretoTable.AddCell(paretoTableCell1);

                    paretoTableCell1.Phrase = new Phrase(item.AcumSKUs.ToString("P0"), font9);
                    paretoTable.AddCell(paretoTableCell1);
                }

                document.Add(paretoTable);
                #endregion

                #region Graphics Pareto Sales & Margin

                ((PageEvent)writer.PageEvent).Title = "Appendix";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Format("Graphics Pareto Sales {0} & Margin {0}", currencySymbol);

                document.NewPage();

                PdfPTable graphicsTable = new PdfPTable(new float[] { 50f, 50f });
                graphicsTable.WidthPercentage = 100f;
                PdfPCell graphicsCell;


                //Sales vs Skus
                RadChart salesChart = ReportsHelper.GetLineChart("Pareto Sales vs SKUs", "SKUs %", "Sales %");  //new RadChart();
                salesChart.Width = 310;
                salesChart.Height = 310;
                salesChart.PlotArea.XAxis.MaxValue = 100;
                salesChart.PlotArea.XAxis.MinValue = 0;
                salesChart.PlotArea.XAxis.Step = 10;
                salesChart.PlotArea.XAxis.LayoutMode = Telerik.Charting.Styles.ChartAxisLayoutMode.Normal;
                salesChart.PlotArea.YAxis.MaxValue = 100;
                salesChart.PlotArea.YAxis.MinValue = 0;
                salesChart.PlotArea.YAxis.Step = 10;
                salesChart.Legend.Visible = false;

                ChartSeries s1 = new ChartSeries();
                s1.Type = ChartSeriesType.Spline;
                s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                s1.Appearance.FillStyle.MainColor = barColors[0];

                int skusSample;

                ChartSeriesItem serieItem = new ChartSeriesItem();
                serieItem.XValue = 0d;
                serieItem.YValue = 0d;
                serieItem.Label.Visible = false;
                s1.AddItem(serieItem);

                decimal prevAcumSales = 0;
                foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
                {
                    serieItem = new ChartSeriesItem();
                    serieItem.XValue = (double)item.AcumSKUs * 100d;
                    serieItem.YValue = (double)item.AcumSales * 100d;
                    if (item.AcumSales >= 0.8m && item.PrevAcumSales < 0.8m)
                    {
                        serieItem.Label.Visible = true;
                        serieItem.Label.TextBlock.Text = item.AcumSKUs.ToString("P1");
                        serieItem.Label.TextBlock.Appearance.Border.Color = barColors[0];
                        serieItem.Label.TextBlock.Appearance.Border.Width = 2f;
                    }
                    else
                    {
                        serieItem.Label.Visible = false;
                    }

                    s1.AddItem(serieItem);

                    prevAcumSales = item.Sales;
                }

                serieItem = new ChartSeriesItem();
                serieItem.XValue = 100d;
                serieItem.YValue = 100d;
                serieItem.Label.Visible = false;
                s1.AddItem(serieItem);
                salesChart.Series.Add(s1);

                graphicsCell = new PdfPCell(iTextSharp.text.Image.GetInstance(salesChart.GetBitmap(), BaseColor.WHITE), true);
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = Element.ALIGN_CENTER;
                graphicsCell.PaddingTop = 50f;
                graphicsCell.PaddingLeft = 10f;
                graphicsTable.AddCell(graphicsCell);


                salesChart.ChartTitle.TextBlock.Text = "Pareto Margin vs SKUs";
                salesChart.PlotArea.XAxis.AxisLabel.TextBlock.Text = "SKUs %";
                salesChart.PlotArea.YAxis.AxisLabel.TextBlock.Text = "Margin %";

                s1 = new ChartSeries();
                s1.Type = ChartSeriesType.Spline;
                s1.Appearance.FillStyle.MainColor = barColors[0];

                serieItem = new ChartSeriesItem();
                serieItem.XValue = 0d;
                serieItem.YValue = 0d;
                serieItem.Label.Visible = false;
                s1.AddItem(serieItem);

                decimal prevAcumGM = 0;
                decimal acumGM = 0;
                decimal acumGMP = 0;
                int countGMSKUs = 0;
                foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.GM))
                {
                    countGMSKUs++;
                    acumGM += item.GM;
                    acumGMP = totalGM != 0 ? acumGM / totalGM : 0;

                    serieItem = new ChartSeriesItem();
                    serieItem.XValue = totalSKUs != 0 ? (double)countGMSKUs / totalSKUs * 100d : 0d;
                    serieItem.YValue = (double)acumGMP * 100d;
                    if (acumGMP >= 0.8m && prevAcumGM < 0.8m)
                    {
                        serieItem.Label.Visible = true;
                        serieItem.Label.TextBlock.Text = totalSKUs != 0 ? ((double)countGMSKUs / totalSKUs).ToString("P1") : string.Empty;
                        serieItem.Label.TextBlock.Appearance.Border.Color = barColors[0];
                        serieItem.Label.TextBlock.Appearance.Border.Width = 2f;
                    }
                    else
                    {
                        serieItem.Label.Visible = false;
                    }

                    s1.AddItem(serieItem);

                    prevAcumGM = acumGMP;
                }

                serieItem = new ChartSeriesItem();
                serieItem.XValue = 100d;
                serieItem.YValue = 100d;
                serieItem.Label.Visible = false;
                s1.AddItem(serieItem);

                salesChart.Series.Clear();
                salesChart.Series.Add(s1);

                graphicsCell = new PdfPCell(iTextSharp.text.Image.GetInstance(salesChart.GetBitmap(), BaseColor.WHITE), true);
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = Element.ALIGN_CENTER;
                graphicsCell.PaddingTop = 50f;
                graphicsTable.AddCell(graphicsCell);


                document.Add(graphicsTable);


                #endregion

                #region Store Coverage & SKU Penetration
                IEnumerable<StoreCoverageSegment> group1Rows = null;
                IEnumerable<StoreCoverageSegment> group2Rows = null;

                //Traigo los datos del total red para StoreCoverage y Penetration
                var storeCoverageRows = ReportsRepository.GetStoreCoveragePenetration(rangeReview.Id, category.Id);

                int storeCoverageColumns = 5;
                if (storeCoverageRows.Count > 0)
                {
                    string segmentation1 = storeCoverageRows.First().StoreSegmentation1;
                    string segmentation2 = storeCoverageRows.First().StoreSegmentation2;
                    if (!string.IsNullOrEmpty(segmentation1))
                    {
                        switch (segmentation1)
                        {
                            case "Region":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Region, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Region, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Subregion":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Subregion, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Subregion, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "City":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.City, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.City, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "State":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.State, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.State, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SEL":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SEL, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SEL, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "ShoppingOccasion":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.ShoppingOccasion, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.ShoppingOccasion, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Size":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Size, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Size, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Format":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Format, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Format, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "ShopType":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.ShopType, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.ShopType, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Layout":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Layout, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Layout, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "OpeningHours":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.OpeningHours, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.OpeningHours, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SELCustomers":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SELCustomers, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SELCustomers, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SELLocation":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SELLocation, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SELLocation, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Attribute1":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Attribute1, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Attribute1, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Attribute2":
                                group1Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Attribute2, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Attribute2, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;

                        }
                    }

                    if (!string.IsNullOrEmpty(segmentation2))
                    {
                        switch (segmentation2)
                        {
                            case "Region":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Region, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Region, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Subregion":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Subregion, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Subregion, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "City":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.City, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.City, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "State":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.State, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.State, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SEL":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SEL, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SEL, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "ShoppingOccasion":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.ShoppingOccasion, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.ShoppingOccasion, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Size":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Size, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Size, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Format":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Format, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Format, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "ShopType":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.ShopType, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.ShopType, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Layout":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Layout, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Layout, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "OpeningHours":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.OpeningHours, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.OpeningHours, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SELCustomers":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SELCustomers, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SELCustomers, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "SELLocation":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.SELLocation, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.SELLocation, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Attribute1":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Attribute1, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Attribute1, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;
                            case "Attribute2":
                                group2Rows = (from s in storeCoverageRows
                                              where s.SKUPenetration
                                              group s by new { s.Attribute2, s.ArticleId, s.StoreId }
                                                  into g
                                                  select new StoreCoverageSegment { StoreId = g.Key.StoreId, Segment = g.Key.Attribute2, ArticleId = g.Key.ArticleId, Sales = g.Sum(x => x.Sales) });
                                break;

                        }
                    }
                }

                #region SKU Penetration. Top 80% Sales
                if (setup.Penetration)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "SKU Penetration: Top 80% sales";

                    document.NewPage();


                    if (storeCoverageRows.Count > 0)
                    {
                        if (group1Rows != null)
                        {
                            storeCoverageColumns += group1Rows.Select(x => x.Segment).Distinct().Count();
                        }
                        if (group2Rows != null)
                        {
                            storeCoverageColumns += group2Rows.Select(x => x.Segment).Distinct().Count();
                        }
                    }

                    PdfPTable storeCoverageTable = new PdfPTable(storeCoverageColumns);
                    float[] storeCoverageWidths = new float[storeCoverageColumns];
                    storeCoverageWidths.SetValue(3f, 0);
                    storeCoverageWidths.SetValue(10f, 1);
                    storeCoverageWidths.SetValue(25f, 2);
                    storeCoverageWidths.SetValue(20f, 3);
                    for (int i = 4; i < storeCoverageColumns; i++)
                    {
                        storeCoverageWidths.SetValue(8f, i);
                    }
                    storeCoverageTable.SetWidths(storeCoverageWidths);
                    storeCoverageTable.WidthPercentage = 95f;
                    storeCoverageTable.SplitLate = true;
                    storeCoverageTable.SplitRows = true;
                    storeCoverageTable.HeaderRows = 4;
                    storeCoverageTable.FooterRows = 2;
                    emptyCell.Colspan = storeCoverageColumns;

                    storeCoverageTable.AddCell(emptyCell);

                    PdfPCell storeCoverageCell = new PdfPCell(new Phrase("#", font9bold));
                    storeCoverageCell.Padding = 4f;
                    storeCoverageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    storeCoverageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    storeCoverageCell.BackgroundColor = new BaseColor(216, 228, 188);
                    storeCoverageCell.BorderWidth = 1;
                    storeCoverageCell.BorderColor = BaseColor.LIGHT_GRAY;
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Article", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Description", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Subcategory", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Total", font9);
                    storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    if (group1Rows != null)
                    {
                        foreach (var title in group1Rows.Select(x => x.Segment).Distinct())
                        {
                            storeCoverageCell.Phrase = new Phrase(title, font9);
                            storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                            storeCoverageTable.AddCell(storeCoverageCell);
                        }
                    }

                    if (group2Rows != null)
                    {
                        foreach (var title in group2Rows.Select(x => x.Segment).Distinct())
                        {
                            storeCoverageCell.Phrase = new Phrase(title, font9);
                            storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                            storeCoverageTable.AddCell(storeCoverageCell);
                        }
                    }

                    //2 rows vacios para el footer.
                    storeCoverageTable.AddCell(emptyCell);
                    storeCoverageTable.AddCell(emptyCell);

                    storeCoverageCell.BackgroundColor = BaseColor.WHITE;

                    //TODO: se asume que no hay diferencias en la muestra de tiendas que entran en el store coverage con las del penetration
                    decimal totalNetworkSales = storeCoverageRows.Where(x => x.SKUPenetration).Sum(x => x.Sales);

                    int num = 0;
                    acumSales = 0;
                    var storeCoverageByArticle = (from s in storeCoverageRows group s by s.ArticleId into g select new { ArticleId = g.Key, Sales = g.Sum(x => x.Sales) }).OrderByDescending(x => x.Sales);
                    decimal maxSalesP = totalNetworkSales != 0 ? storeCoverageByArticle.First().Sales / totalNetworkSales : 0;

                    storeCoverageCell.VerticalAlignment = Element.ALIGN_BASELINE;
                    foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
                    {
                        item.Ranking = ++num;
                        item.PrevAcumSales = acumSales / totalSales;
                        acumSales += item.Sales;
                        item.AcumSales = acumSales / totalSales;

                        if (item.PrevAcumSales < 0.8m)
                        {
                            storeCoverageCell.Phrase = new Phrase(num.ToString(), font10);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Code, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Name, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_LEFT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Subcategory, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_LEFT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            decimal itemSales = storeCoverageByArticle.Where(x => x.ArticleId == item.Id).Sum(x => x.Sales);

                            PdfPCell cell = new PdfPCell();
                            cell.Phrase = totalNetworkSales != 0 ? new Phrase((itemSales / totalNetworkSales).ToString("P0"), font9) : new Phrase("");

                            float div = totalNetworkSales != 0 ? (float)itemSales / (float)totalNetworkSales : 0;
                            div = maxSalesP != 0 ? div / (float)maxSalesP : 0;

                            cell.CellEvent = new FillCell(div);
                            storeCoverageTable.AddCell(cell);

                            if (group1Rows != null)
                            {
                                foreach (var segment in group1Rows.Select(x => x.Segment).Distinct())
                                {
                                    var totalSegmentSales = group1Rows.Where(x => x.Segment == segment).Sum(x => x.Sales);
                                    decimal maxSalesSegmentP = (from g in group1Rows where g.Segment == segment group g by g.ArticleId into gr select new { Sales = gr.Sum(x => x.Sales) }).OrderByDescending(x => x.Sales).First().Sales / totalSegmentSales;
                                    var itemSegmentSales = group1Rows.Where(x => x.ArticleId == item.Id && x.Segment == segment).Sum(x => x.Sales);
                                    cell.Phrase = totalSegmentSales != 0 ? new Phrase((itemSegmentSales / totalSegmentSales).ToString("P0"), font9) : new Phrase("");
                                    cell.CellEvent = new FillCell((float)itemSegmentSales / (float)totalSegmentSales / (float)maxSalesSegmentP);
                                    storeCoverageTable.AddCell(cell);
                                }
                            }

                            if (group2Rows != null)
                            {
                                foreach (var segment in group2Rows.Select(x => x.Segment).Distinct())
                                {
                                    var totalSegmentSales = group2Rows.Where(x => x.Segment == segment).Sum(x => x.Sales);
                                    decimal maxSalesSegmentP = (from g in group2Rows where g.Segment == segment group g by g.ArticleId into gr select new { Sales = gr.Sum(x => x.Sales) }).OrderByDescending(x => x.Sales).First().Sales / totalSegmentSales;
                                    var itemSegmentSales = group2Rows.Where(x => x.ArticleId == item.Id && x.Segment == segment).Sum(x => x.Sales);
                                    cell.Phrase = totalSegmentSales != 0 ? new Phrase((itemSegmentSales / totalSegmentSales).ToString("P0"), font9) : new Phrase("");
                                    cell.CellEvent = new FillCell((float)itemSegmentSales / (float)totalSegmentSales / (float)maxSalesSegmentP);
                                    storeCoverageTable.AddCell(cell);
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    document.Add(storeCoverageTable);
                }
                #endregion

                #region Store Coverage
                if (setup.Coverage)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Store Coverage per SKU. Top 80% sales";

                    document.NewPage();
                    storeCoverageColumns = storeCoverageColumns + 3;
                    float[] storeCoverageWidths2 = new float[storeCoverageColumns];
                    storeCoverageWidths2.SetValue(3f, 0);
                    storeCoverageWidths2.SetValue(10f, 1);
                    storeCoverageWidths2.SetValue(25f, 2);
                    storeCoverageWidths2.SetValue(20f, 3);
                    storeCoverageWidths2.SetValue(8f, 4);
                    storeCoverageWidths2.SetValue(8f, 5);
                    storeCoverageWidths2.SetValue(8f, 6);
                    for (int i = 7; i < storeCoverageColumns; i++)
                    {
                        storeCoverageWidths2.SetValue(8f, i);
                    }
                    PdfPTable storeCoverageTable = new PdfPTable(storeCoverageColumns);
                    storeCoverageTable.SetWidths(storeCoverageWidths2);
                    storeCoverageTable.WidthPercentage = 95f;
                    storeCoverageTable.SplitLate = true;
                    storeCoverageTable.SplitRows = true;
                    storeCoverageTable.HeaderRows = 4;
                    storeCoverageTable.FooterRows = 2;
                    emptyCell.Colspan = storeCoverageColumns;

                    storeCoverageTable.AddCell(emptyCell);

                    PdfPCell storeCoverageCell = new PdfPCell(new Phrase("#", font9bold));
                    storeCoverageCell.Padding = 4f;
                    storeCoverageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    storeCoverageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    storeCoverageCell.BackgroundColor = new BaseColor(216, 228, 188);
                    storeCoverageCell.BorderWidth = 1;
                    storeCoverageCell.BorderColor = BaseColor.LIGHT_GRAY;
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Article", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Description", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Subcategory", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Sales", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Sales %", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("Store Coverage", font9);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    storeCoverageCell.Phrase = new Phrase("TOTAL", font9);
                    storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                    storeCoverageTable.AddCell(storeCoverageCell);

                    if (group1Rows != null)
                    {
                        foreach (var title in group1Rows.Select(x => x.Segment).Distinct())
                        {
                            storeCoverageCell.Phrase = new Phrase(title, font9);
                            storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                            storeCoverageTable.AddCell(storeCoverageCell);
                        }
                    }

                    if (group2Rows != null)
                    {
                        foreach (var title in group2Rows.Select(x => x.Segment).Distinct())
                        {
                            storeCoverageCell.Phrase = new Phrase(title, font9);
                            storeCoverageCell.BackgroundColor = new BaseColor(117, 147, 61);
                            storeCoverageTable.AddCell(storeCoverageCell);
                        }
                    }

                    storeCoverageTable.AddCell(emptyCell);
                    storeCoverageTable.AddCell(emptyCell);
                    storeCoverageCell.BackgroundColor = BaseColor.WHITE;

                    int num = 0;
                    acumSales = 0;
                    foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
                    {
                        item.Ranking = ++num;
                        item.PrevAcumSales = acumSales / totalSales;
                        acumSales += item.Sales;
                        item.AcumSales = acumSales / totalSales;

                        if (item.PrevAcumSales < 0.8m)
                        {
                            storeCoverageCell.Phrase = new Phrase(num.ToString(), font10);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Code, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Name, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_LEFT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Subcategory, font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_LEFT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.Sales.ToString("C2"), font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(item.AcumSales.ToString("P0"), font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase((storeCoverageRows.Where(x => x.ArticleId == item.Id).Count() / (decimal)storeCoverageRows.First().TotalStoresCoverage).ToString("P0"), font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            storeCoverageCell.Phrase = new Phrase(storeCoverageRows.Where(x => x.ArticleId == item.Id).Count().ToString(), font9);
                            storeCoverageCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            storeCoverageTable.AddCell(storeCoverageCell);

                            if (group1Rows != null)
                            {
                                foreach (var segment in group1Rows.Select(x => x.Segment).Distinct())
                                {
                                    storeCoverageCell.Phrase = new Phrase(group1Rows.Where(x => x.ArticleId == item.Id && x.Segment == segment).Count().ToString("N0"), font9);
                                    storeCoverageTable.AddCell(storeCoverageCell);
                                }
                            }

                            if (group2Rows != null)
                            {
                                foreach (var segment in group2Rows.Select(x => x.Segment).Distinct())
                                {
                                    storeCoverageCell.Phrase = new Phrase(group2Rows.Where(x => x.ArticleId == item.Id && x.Segment == segment).Count().ToString("N0"), font9);
                                    storeCoverageTable.AddCell(storeCoverageCell);
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    document.Add(storeCoverageTable);
                }
                #endregion

                #endregion

                #region Category Dynamics and Trends
                if (setup.DynamicsBrand || setup.DynamicsManufacturer)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Category Dynamics and Trends";
                    document.NewPage();

                    var salesBySkuType = from item in paretoItemsWithPY
                                         group item by new { item.Id, item.Code, item.Name, item.Brand, item.Category, item.Subcategory } into g
                                         select new
                                         {
                                             ArticleId = g.Key.Id,
                                             Code = g.Key.Code,
                                             Name = g.Key.Name,
                                             Brand = g.Key.Brand,
                                             Category = g.Key.Category,
                                             Subcategory = g.Key.Subcategory,
                                             Units = g.Sum(x => x.Units),
                                             UnitsCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Units),
                                             UnitsPY = g.Where(x => x.IsPriorYear).Sum(x => x.Units),
                                             Sales = g.Sum(x => x.Sales),
                                             SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                             SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                             Margin = g.Sum(x => x.GM),
                                             MarginCY = g.Where(x => !x.IsPriorYear).Sum(x => x.GM),
                                             MarginPY = g.Where(x => x.IsPriorYear).Sum(x => x.GM),
                                             Status = (g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0) ? SKUStatus.Active :
                                                       g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) == 0 ? SKUStatus.New :
                                                       g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) == 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0 ? SKUStatus.Delisted : SKUStatus.None
                                         };

                    var salesByStatus = from item in salesBySkuType
                                        group item by new { item.Status } into g
                                        select new
                                        {
                                            Status = g.Key.Status,
                                            SalesCY = g.Sum(x => x.SalesCY),
                                            SalesPY = g.Sum(x => x.SalesPY),
                                            MarginCY = g.Sum(x => x.MarginCY),
                                            MarginPY = g.Sum(x => x.MarginPY),
                                            SKUsCY = g.Count(x => x.SalesCY > 0),
                                            SKUsPY = g.Count(x => x.SalesPY > 0)
                                        };

                    PdfPTable dynamicsTable = new PdfPTable(new float[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 });
                    dynamicsTable.WidthPercentage = 95;
                    dynamicsTable.SpacingBefore = 30;

                    emptyCell.Rowspan = 2;
                    emptyCell.Colspan = 1;
                    dynamicsTable.AddCell(emptyCell);

                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(31, 73, 125);
                    dynamicsTable.DefaultCell.Colspan = 5;
                    dynamicsTable.AddCell(new Phrase("CY", font10white));
                    dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(155, 187, 89);
                    dynamicsTable.AddCell(new Phrase("PY", font10white));
                    dynamicsTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    dynamicsTable.DefaultCell.Colspan = 1;
                    dynamicsTable.AddCell(new Phrase("# SKUs", font10));
                    dynamicsTable.AddCell(new Phrase("Sales " + currencySymbol, font10));
                    dynamicsTable.AddCell(new Phrase("Sales %", font10));
                    dynamicsTable.AddCell(new Phrase("GIM " + currencySymbol, font10));
                    dynamicsTable.AddCell(new Phrase("GIM %", font10));
                    dynamicsTable.AddCell(new Phrase("# SKUs", font10));
                    dynamicsTable.AddCell(new Phrase("Sales " + currencySymbol, font10));
                    dynamicsTable.AddCell(new Phrase("Sales %", font10));
                    dynamicsTable.AddCell(new Phrase("GIM " + currencySymbol, font10));
                    dynamicsTable.AddCell(new Phrase("GIM %", font10));

                    var activeSKUsSales = salesByStatus.SingleOrDefault(x => x.Status == SKUStatus.Active);
                    var newSKUsSales = salesByStatus.SingleOrDefault(x => x.Status == SKUStatus.New);
                    var delistedSKUsSales = salesByStatus.SingleOrDefault(x => x.Status == SKUStatus.Delisted);

                    var activeSecured = activeSKUsSales ?? new { Status = SKUStatus.Active, SalesCY = 0m, SalesPY = 0m, MarginCY = 0m, MarginPY = 0m, SKUsCY = 0, SKUsPY = 0 };
                    var newSecured = newSKUsSales ?? new { Status = SKUStatus.New, SalesCY = 0m, SalesPY = 0m, MarginCY = 0m, MarginPY = 0m, SKUsCY = 0, SKUsPY = 0 };
                    var delistedSecured = delistedSKUsSales ?? new { Status = SKUStatus.Delisted, SalesCY = 0m, SalesPY = 0m, MarginCY = 0m, MarginPY = 0m, SKUsCY = 0, SKUsPY = 0 };

                    var totalSKUsSales = new
                    {
                        SalesCY = activeSecured.SalesCY + newSecured.SalesCY + delistedSecured.SalesCY,
                        SalesPY = activeSecured.SalesPY + newSecured.SalesPY + delistedSecured.SalesPY,
                        MarginCY = activeSecured.MarginCY + newSecured.MarginCY + delistedSecured.MarginCY,
                        MarginPY = activeSecured.MarginPY + newSecured.MarginPY + delistedSecured.MarginPY,
                        SKUsCY = activeSecured.SKUsCY + newSecured.SKUsCY + delistedSecured.SKUsCY,
                        SKUsPY = activeSecured.SKUsPY + newSecured.SKUsPY + delistedSecured.SKUsPY,
                    };

                    //Active SKUs                

                    dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    dynamicsTable.AddCell(new Phrase("Active", font10));
                    if (activeSKUsSales != null)
                    {
                        dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.SKUsCY.ToString("N0"), font10));
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.SalesCY.ToString("C2"), font10));
                        dynamicsTable.AddCell(new Phrase((activeSKUsSales.SalesCY / totalSKUsSales.SalesCY).ToString("P1"), font10));
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.MarginCY.ToString("C2"), font10));
                        dynamicsTable.AddCell(new Phrase((activeSKUsSales.MarginCY / totalSKUsSales.MarginCY).ToString("P1"), font10));
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.SKUsPY.ToString("N0"), font10));
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.SalesPY.ToString("C2"), font10));
                        dynamicsTable.AddCell(new Phrase((activeSKUsSales.SalesPY / totalSKUsSales.SalesPY).ToString("P1"), font10));
                        dynamicsTable.AddCell(new Phrase(activeSKUsSales.MarginPY.ToString("C2"), font10));
                        dynamicsTable.AddCell(new Phrase((activeSKUsSales.MarginPY / totalSKUsSales.MarginPY).ToString("P1"), font10));
                    }
                    else
                    {
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                    }

                    //New SKUs                

                    dynamicsTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    dynamicsTable.AddCell(new Phrase("New", font10));
                    if (newSKUsSales != null)
                    {
                        dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        dynamicsTable.AddCell(new Phrase(newSKUsSales.SKUsCY != 0 ? newSKUsSales.SKUsCY.ToString("N0") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(newSKUsSales.SalesCY != 0 ? newSKUsSales.SalesCY.ToString("C2") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(newSKUsSales.SalesCY != 0 ? (newSKUsSales.SalesCY / totalSKUsSales.SalesCY).ToString("P1") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(newSKUsSales.MarginCY != 0 ? newSKUsSales.MarginCY.ToString("C2") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(newSKUsSales.MarginCY != 0 ? (newSKUsSales.MarginCY / totalSKUsSales.MarginCY).ToString("P1") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                    }
                    else
                    {
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                    }
                    //Delisted SKUs                

                    dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    dynamicsTable.AddCell(new Phrase("Delisted", font10));
                    if (delistedSKUsSales != null)
                    {
                        dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(delistedSKUsSales.SKUsPY != 0 ? delistedSKUsSales.SKUsPY.ToString("N0") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(delistedSKUsSales.SalesPY != 0 ? delistedSKUsSales.SalesPY.ToString("C2") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(totalSKUsSales.SalesPY != 0 && delistedSKUsSales.SalesPY != 0 ? (delistedSKUsSales.SalesPY / totalSKUsSales.SalesPY).ToString("P1") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(delistedSKUsSales.MarginPY != 0 ? delistedSKUsSales.MarginPY.ToString("C2") : string.Empty, font10));
                        dynamicsTable.AddCell(new Phrase(totalSKUsSales.MarginPY != 0 && delistedSKUsSales.MarginPY != 0 ? (delistedSKUsSales.MarginPY / totalSKUsSales.MarginPY).ToString("P1") : string.Empty, font10));
                    }
                    else
                    {
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                        dynamicsTable.AddCell(new Phrase(string.Empty, font));
                    }

                    //Totales
                    emptyCell.Rowspan = 1;
                    emptyCell.Colspan = 1;
                    dynamicsTable.AddCell(emptyCell);
                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    dynamicsTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SKUsCY != 0 ? totalSKUsSales.SKUsCY.ToString("N0") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SalesCY != 0 ? totalSKUsSales.SalesCY.ToString("C2") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SalesCY != 0 ? "100,0%" : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.MarginCY != 0 ? totalSKUsSales.MarginCY.ToString("C2") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.MarginCY != 0 ? "100,0%" : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SKUsPY != 0 ? totalSKUsSales.SKUsPY.ToString("N0") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SalesPY != 0 ? totalSKUsSales.SalesPY.ToString("C2") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.SalesPY != 0 ? "100,0%" : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.MarginPY != 0 ? totalSKUsSales.MarginPY.ToString("C2") : string.Empty, font10));
                    dynamicsTable.AddCell(new Phrase(totalSKUsSales.MarginPY != 0 ? "100,0%" : string.Empty, font10));

                    document.Add(dynamicsTable);
                    Paragraph para = null;
                    if (salesBySkuType.Any(x => x.SalesPY == 0m && paretoItems.Where(p => !p.IsDeletedRangeReview).Any(p => p.Id == x.ArticleId)))
                    {
                        para = new Paragraph("New SKUs are highlighted in Pareto Sales & Margins lists.", font10);
                        para.IndentationLeft = 20;
                        para.SpacingBefore = 15;
                        document.Add(para);
                    }
                    else
                    {
                        para = new Paragraph(" ");
                        para.IndentationLeft = 20;
                        para.SpacingBefore = 15;
                        document.Add(para);
                    }


                    var delistedSkus = salesBySkuType.Where(x => x.Status == SKUStatus.Delisted);

                    if (delistedSkus.Any())
                    {
                        para = new Paragraph("De-listed SKUs", font13bold);
                        para.IndentationLeft = 20;
                        para.SpacingBefore = 20;
                        document.Add(para);

                        PdfPTable delistedSalesTable = new PdfPTable(new float[] { 8, 20, 12, 6, 6, 6 });
                        delistedSalesTable.WidthPercentage = 70;
                        delistedSalesTable.SpacingBefore = 5;
                        delistedSalesTable.HeaderRows = 6;
                        delistedSalesTable.FooterRows = 3;
                        emptyTableCell.Colspan = 6;

                        delistedSalesTable.AddCell(emptyTableCell);
                        emptyCell.Colspan = 3;
                        delistedSalesTable.AddCell(emptyCell);
                        delistedSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        delistedSalesTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                        delistedSalesTable.DefaultCell.BackgroundColor = new BaseColor(49, 132, 155);
                        delistedSalesTable.DefaultCell.Colspan = 3;
                        delistedSalesTable.AddCell(new Phrase("PY", font10white));
                        delistedSalesTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                        delistedSalesTable.DefaultCell.Colspan = 1;
                        delistedSalesTable.AddCell(new Phrase("Article Nº", font10));
                        delistedSalesTable.AddCell(new Phrase("Description", font10));
                        delistedSalesTable.AddCell(new Phrase("Brand", font10));
                        delistedSalesTable.DefaultCell.BackgroundColor = new BaseColor(49, 132, 155);
                        delistedSalesTable.AddCell(new Phrase("Volume", font10white));
                        delistedSalesTable.AddCell(new Phrase("Sales " + currencySymbol, font10white));
                        delistedSalesTable.AddCell(new Phrase("Sales Contr.", font10white));

                        delistedSalesTable.AddCell(emptyTableCell);
                        delistedSalesTable.AddCell(emptyTableCell);
                        delistedSalesTable.AddCell(emptyTableCell);

                        decimal delistedTotalPYSales = delistedSkus.Sum(x => x.SalesPY);
                        delistedSalesTable.DefaultCell.BackgroundColor = new BaseColor(255, 153, 153);
                        foreach (var item in delistedSkus.OrderByDescending(x => x.SalesPY))
                        {
                            delistedSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            delistedSalesTable.AddCell(new Phrase(item.Code, font10));
                            delistedSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            delistedSalesTable.AddCell(new Phrase(item.Name, font10));
                            delistedSalesTable.AddCell(new Phrase(item.Brand, font10));
                            delistedSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            delistedSalesTable.AddCell(new Phrase(item.UnitsPY.ToString("N0"), font10));
                            delistedSalesTable.AddCell(new Phrase(item.SalesPY.ToString("C2"), font10));
                            delistedSalesTable.AddCell(new Phrase((item.SalesPY / delistedTotalPYSales).ToString("P1"), font10));
                        }

                        document.Add(delistedSalesTable);
                    }
                }
                #endregion

                #region Manufacturer CY vs PY
                decimal totalSalesPY = paretoItemsWithPY.Where(x => x.IsPriorYear).Sum(x => x.Sales);
                decimal totalSalesCY = paretoItemsWithPY.Where(x => !x.IsPriorYear).Sum(x => x.Sales);
                if (setup.DynamicsManufacturer)
                {
                    if (totalSalesPY > 0 && totalSalesCY > 0)
                    {
                        ((PageEvent)writer.PageEvent).Title = "Appendix";
                        ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Manufacturer";
                        ((PageEvent)writer.PageEvent).SubTitleSecondLine = "CY vs. PY";
                        document.NewPage();

                        var manuQuery = from item in paretoItemsWithPY
                                        group item by item.Manufacturer.ToUpper() into g
                                        select new
                                        {
                                            Manufacturer = g.Key,
                                            UnitsCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Units),
                                            UnitsPY = g.Where(x => x.IsPriorYear).Sum(x => x.Units),
                                            SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                            SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                            SalesPercCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) / totalSalesCY,
                                            SalesPercPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales) / totalSalesPY,
                                        };


                        PdfPTable manufacturerSalesTable = new PdfPTable(new float[] { 15, 6, 6, 6, 6 });
                        manufacturerSalesTable.WidthPercentage = 50;
                        manufacturerSalesTable.SpacingBefore = 20;
                        manufacturerSalesTable.HeaderRows = 6;
                        manufacturerSalesTable.FooterRows = 3;
                        emptyTableCell.Colspan = 5;

                        manufacturerSalesTable.AddCell(emptyTableCell);
                        emptyCell.Colspan = 1;
                        manufacturerSalesTable.AddCell(emptyCell);
                        manufacturerSalesTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                        manufacturerSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        manufacturerSalesTable.DefaultCell.Colspan = 3;
                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(217, 151, 149);
                        manufacturerSalesTable.AddCell(new Phrase("CY vs. PY", font10));
                        manufacturerSalesTable.DefaultCell.Colspan = 1;
                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                        manufacturerSalesTable.AddCell(new Phrase("CY", font10));

                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(184, 204, 228);
                        manufacturerSalesTable.AddCell(new Phrase("Manufacturer", font10));
                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(217, 151, 149);
                        manufacturerSalesTable.AddCell(new Phrase("Volume", font10));
                        manufacturerSalesTable.AddCell(new Phrase("Sales " + currencySymbol, font10));
                        manufacturerSalesTable.AddCell(new Phrase("Sales %", font10));
                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                        manufacturerSalesTable.AddCell(new Phrase("Sales %", font10));

                        manufacturerSalesTable.AddCell(emptyTableCell);
                        manufacturerSalesTable.AddCell(emptyTableCell);
                        manufacturerSalesTable.AddCell(emptyTableCell);

                        var manufacturerQuery = from item in manuQuery
                                                select new
                                                {
                                                    Manufacturer = item.Manufacturer,
                                                    UnitsCY = item.UnitsCY,
                                                    UnitsPY = item.UnitsPY,
                                                    SalesCY = item.SalesCY,
                                                    SalesPY = item.SalesPY,
                                                    SalesPercCY = item.SalesPercCY,
                                                    SalesPercPY = item.SalesPercPY,
                                                    UnitsGrowth = item.UnitsPY != 0 ? item.UnitsCY / item.UnitsPY - 1 : 1,
                                                    SalesGrowth = item.SalesPY != 0 ? item.SalesCY / item.SalesPY - 1 : 1,
                                                    SalesPercGrowth = item.SalesPercCY - item.SalesPercPY
                                                };


                        manufacturerSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                        foreach (var item in manufacturerQuery.Where(x => x.SalesPercCY > 0m).OrderByDescending(x => x.SalesPercCY))
                        {
                            manufacturerSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            manufacturerSalesTable.AddCell(new Phrase(item.Manufacturer, font10));
                            manufacturerSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            manufacturerSalesTable.AddCell(new Phrase(item.UnitsGrowth.ToString("P1"), font10));
                            manufacturerSalesTable.AddCell(new Phrase(item.SalesGrowth.ToString("P1"), font10));
                            manufacturerSalesTable.AddCell(new Phrase(item.SalesPercGrowth.ToString("P1"), font10));
                            manufacturerSalesTable.AddCell(new Phrase(item.SalesPercCY.ToString("P1"), font10));
                        }

                        //Agrego el Total
                        manufacturerSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                        manufacturerSalesTable.AddCell(new Phrase(string.Empty));
                        manufacturerSalesTable.AddCell(new Phrase(manuQuery.Sum(x => x.UnitsPY) != 0 ? (manuQuery.Sum(x => x.UnitsCY) / manuQuery.Sum(x => x.UnitsPY) - 1).ToString("P1") : string.Empty, font10));
                        manufacturerSalesTable.AddCell(new Phrase(manuQuery.Sum(x => x.SalesPY) != 0 ? (manuQuery.Sum(x => x.SalesCY) / manuQuery.Sum(x => x.SalesPY) - 1).ToString("P1") : string.Empty, font10));
                        manufacturerSalesTable.AddCell(new Phrase(string.Empty));
                        manufacturerSalesTable.AddCell(new Phrase("100 %", font10));

                        document.Add(manufacturerSalesTable);
                    }
                }
                #endregion

                #region Brand & Subcategory CY vs PY
                if (setup.DynamicsBrand)
                {
                    if (totalSalesPY > 0 && totalSalesCY > 0)
                    {
                        ((PageEvent)writer.PageEvent).Title = "Appendix";
                        ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Brand & Subcategory";
                        ((PageEvent)writer.PageEvent).SubTitleSecondLine = "CY vs. PY";
                        document.NewPage();

                        var brandQuery = from item in paretoItemsWithPY
                                         group item by new { Brand = !string.IsNullOrEmpty(item.Brand) ? item.Brand.ToUpper() : "Falta Completar", Subcategory = item.Subcategory } into g
                                         select new
                                         {
                                             Brand = g.Key.Brand,
                                             Subcategory = g.Key.Subcategory,
                                             UnitsCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Units),
                                             UnitsPY = g.Where(x => x.IsPriorYear).Sum(x => x.Units),
                                             SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                             SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                             SalesPercCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) / totalSalesCY,
                                             SalesPercPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales) / totalSalesPY,
                                         };

                        var subcategoryQuery = from item in paretoItemsWithPY
                                               group item by new { item.Subcategory } into g
                                               select new
                                               {
                                                   Subcategory = g.Key.Subcategory,
                                                   UnitsCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Units),
                                                   UnitsPY = g.Where(x => x.IsPriorYear).Sum(x => x.Units),
                                                   SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                                   SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                                   SalesPercCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) / totalSalesCY,
                                                   SalesPercPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales) / totalSalesPY,
                                               };


                        PdfPTable brandSalesTable = new PdfPTable(new float[] { 15, 6, 6, 6, 6 });
                        brandSalesTable.WidthPercentage = 50;
                        brandSalesTable.HeaderRows = 6;
                        brandSalesTable.FooterRows = 3;
                        emptyTableCell.Colspan = 5;

                        brandSalesTable.AddCell(emptyTableCell);
                        emptyCell.Colspan = 1;
                        brandSalesTable.AddCell(emptyCell);
                        brandSalesTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                        brandSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        brandSalesTable.DefaultCell.Colspan = 3;
                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(217, 151, 149);
                        brandSalesTable.AddCell(new Phrase("CY vs. PY", font10));
                        brandSalesTable.DefaultCell.Colspan = 1;
                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                        brandSalesTable.AddCell(new Phrase("CY", font10));

                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(184, 204, 228);
                        brandSalesTable.AddCell(new Phrase("Brand", font10));
                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(217, 151, 149);
                        brandSalesTable.AddCell(new Phrase("Volume", font10));
                        brandSalesTable.AddCell(new Phrase("Sales " + currencySymbol, font10));
                        brandSalesTable.AddCell(new Phrase("Sales %", font10));
                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                        brandSalesTable.AddCell(new Phrase("Sales %", font10));

                        brandSalesTable.AddCell(emptyTableCell);
                        brandSalesTable.AddCell(emptyTableCell);
                        brandSalesTable.AddCell(emptyTableCell);

                        var brandFinalQuery = from item in brandQuery
                                              select new
                                              {
                                                  Brand = item.Brand,
                                                  Subcategory = item.Subcategory,
                                                  UnitsCY = item.UnitsCY,
                                                  UnitsPY = item.UnitsPY,
                                                  SalesCY = item.SalesCY,
                                                  SalesPY = item.SalesPY,
                                                  SalesPercCY = item.SalesPercCY,
                                                  SalesPercPY = item.SalesPercPY,
                                                  UnitsGrowth = item.UnitsPY != 0 ? item.UnitsCY / item.UnitsPY - 1 : 1,
                                                  SalesGrowth = item.SalesPY != 0 ? item.SalesCY / item.SalesPY - 1 : 1,
                                                  SalesPercGrowth = item.SalesPercCY - item.SalesPercPY
                                              };

                        var subcategoryFinalQuery = from item in subcategoryQuery
                                                    select new
                                                    {
                                                        Subcategory = item.Subcategory,
                                                        UnitsCY = item.UnitsCY,
                                                        UnitsPY = item.UnitsPY,
                                                        SalesCY = item.SalesCY,
                                                        SalesPY = item.SalesPY,
                                                        SalesPercCY = item.SalesPercCY,
                                                        SalesPercPY = item.SalesPercPY,
                                                        UnitsGrowth = item.UnitsPY != 0 ? item.UnitsCY / item.UnitsPY - 1 : 1,
                                                        SalesGrowth = item.SalesPY != 0 ? item.SalesCY / item.SalesPY - 1 : 1,
                                                        SalesPercGrowth = item.SalesPercCY - item.SalesPercPY
                                                    };


                        foreach (var subcategoryItem in subcategoryFinalQuery.Where(x => x.SalesPercCY > 0).OrderByDescending(x => x.SalesPercCY))
                        {
                            brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                            brandSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            brandSalesTable.AddCell(new Phrase(subcategoryItem.Subcategory, font10));
                            brandSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            brandSalesTable.AddCell(new Phrase(subcategoryItem.UnitsGrowth.ToString("P1"), font10));
                            brandSalesTable.AddCell(new Phrase(subcategoryItem.SalesGrowth.ToString("P1"), font10));
                            brandSalesTable.AddCell(new Phrase(subcategoryItem.SalesPercGrowth.ToString("P1"), font10));
                            brandSalesTable.AddCell(new Phrase(subcategoryItem.SalesPercCY.ToString("P1"), font10));


                            foreach (var brandItem in brandFinalQuery.Where(x => x.Subcategory == subcategoryItem.Subcategory && x.SalesPercCY > 0).OrderByDescending(x => x.SalesPercCY))
                            {
                                brandSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                                brandSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                                brandSalesTable.AddCell(new Phrase(brandItem.Brand, font10));
                                brandSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                brandSalesTable.AddCell(new Phrase(brandItem.UnitsGrowth.ToString("P1"), font10));
                                brandSalesTable.AddCell(new Phrase(brandItem.SalesGrowth.ToString("P1"), font10));
                                brandSalesTable.AddCell(new Phrase(brandItem.SalesPercGrowth.ToString("P1"), font10));
                                brandSalesTable.AddCell(new Phrase(brandItem.SalesPercCY.ToString("P1"), font10));
                            }
                        }

                        //Agrego el Total
                        brandSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                        brandSalesTable.AddCell(new Phrase(string.Empty));
                        brandSalesTable.AddCell(new Phrase(subcategoryQuery.Sum(x => x.UnitsPY) != 0 ? (subcategoryQuery.Sum(x => x.UnitsCY) / subcategoryQuery.Sum(x => x.UnitsPY) - 1).ToString("P1") : string.Empty, font10));
                        brandSalesTable.AddCell(new Phrase(subcategoryQuery.Sum(x => x.SalesPY) != 0 ? (subcategoryQuery.Sum(x => x.SalesCY) / subcategoryQuery.Sum(x => x.SalesPY) - 1).ToString("P1") : string.Empty, font10));
                        brandSalesTable.AddCell(new Phrase(string.Empty));
                        brandSalesTable.AddCell(new Phrase("100 %", font10));

                        document.Add(brandSalesTable);
                    }
                }

                #endregion

                #region Inventory Ratios by SKUs
                PdfPCell greyRow = null;
                int cont = 1;
                if ((setup.DynamicsBrand || setup.DynamicsManufacturer) && setup.Inventory)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Inventory Ratios by SKUs";
                    ((PageEvent)writer.PageEvent).SubTitleSecondLine = "CY vs. PY";
                    document.NewPage();


                    var invQuery = from item in paretoItemsWithPY
                                   where !item.IsDeletedRangeReview
                                   group item by new { item.Code, item.Name, item.Brand } into g
                                   select new
                                   {
                                       Code = g.Key.Code,
                                       Name = g.Key.Name,
                                       Brand = g.Key.Brand.ToUpper(),
                                       InventoryCY = g.Where(x => !x.IsPriorYear).Sum(x => x.InventoryCost),
                                       InventoryPY = g.Where(x => x.IsPriorYear).Sum(x => x.InventoryCost),
                                       SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                       SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                       MarginCY = g.Where(x => !x.IsPriorYear).Sum(x => x.GM),
                                       MarginPY = g.Where(x => x.IsPriorYear).Sum(x => x.GM),
                                   };

                    var invDaysQuery = from item in invQuery
                                       select new
                                       {
                                           Code = item.Code,
                                           Name = item.Name,
                                           Brand = item.Brand.ToUpper(),
                                           InventoryCY = item.InventoryCY,
                                           InventoryPY = item.InventoryPY,
                                           SalesCY = item.SalesCY,
                                           SalesPY = item.SalesPY,
                                           MarginCY = item.MarginCY,
                                           MarginPY = item.MarginPY,
                                           InvDaysCY = (item.SalesCY - item.MarginCY) != 0 ? decimal.Round(item.InventoryCY / ((item.SalesCY - item.MarginCY) / 30), 0) : 0,
                                           InvDaysPY = (item.SalesPY - item.MarginPY) != 0 ? decimal.Round(item.InventoryPY / ((item.SalesPY - item.MarginPY) / 30), 0) : 0,
                                       };

                    var inventoryQuery = from item in invDaysQuery
                                         select new
                                         {
                                             Code = item.Code,
                                             Name = item.Name,
                                             Brand = item.Brand.ToUpper(),
                                             InventoryCY = item.InventoryCY,
                                             InventoryPY = item.InventoryPY,
                                             SalesCY = item.SalesCY,
                                             SalesPY = item.SalesPY,
                                             MarginCY = item.MarginCY,
                                             MarginPY = item.MarginPY,
                                             InvDaysCY = item.InvDaysCY,
                                             InvDaysPY = item.InvDaysPY,
                                             InvDaysGrowth = item.InvDaysPY != 0 ? item.InvDaysCY / item.InvDaysPY - 1 : 1,
                                             InventoryGrowth = item.InventoryPY != 0 ? item.InventoryCY / item.InventoryPY - 1 : 1,
                                         };

                    PdfPTable inventoryTable = new PdfPTable(new float[] { 2, 6, 16, 7, 6, 4, 6, 4, 4, 4 });
                    inventoryTable.WidthPercentage = 95;
                    inventoryTable.HeaderRows = 7;
                    inventoryTable.FooterRows = 3;
                    inventoryTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                    emptyTableCell.Colspan = 10;

                    greyRow = new PdfPCell(new Phrase("The products highlighted increased their Inventory days in CY compared with PY.", font10));
                    greyRow.BackgroundColor = new BaseColor(216, 216, 216);
                    greyRow.Colspan = 10;
                    greyRow.Border = PdfPCell.NO_BORDER;
                    greyRow.Padding = 10;

                    inventoryTable.AddCell(emptyTableCell);
                    inventoryTable.AddCell(greyRow);
                    inventoryTable.AddCell(emptyTableCell);

                    inventoryTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                    inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    inventoryTable.AddCell(new Phrase("#", font10));
                    inventoryTable.AddCell(new Phrase("Article Nº", font10));
                    inventoryTable.AddCell(new Phrase("Description", font10));
                    inventoryTable.AddCell(new Phrase("Brand", font10));
                    inventoryTable.DefaultCell.BackgroundColor = new BaseColor(242, 221, 220);
                    inventoryTable.AddCell(new Phrase(string.Format("Inventory {0} CY", currencySymbol), font10));
                    inventoryTable.AddCell(new Phrase("Inentory Days CY", font10));
                    inventoryTable.DefaultCell.BackgroundColor = new BaseColor(101, 101, 152);
                    inventoryTable.AddCell(new Phrase(string.Format("Inventory {0} PY", currencySymbol), font10));
                    inventoryTable.AddCell(new Phrase("Inentory Days PY", font10));
                    inventoryTable.DefaultCell.BackgroundColor = new BaseColor(178, 161, 199);
                    inventoryTable.AddCell(new Phrase(string.Format("Inventory {0} CY vs. PY", currencySymbol), font10));
                    inventoryTable.AddCell(new Phrase("Inentory Days CY vs. PY", font10));

                    inventoryTable.AddCell(emptyTableCell);
                    inventoryTable.AddCell(emptyTableCell);
                    inventoryTable.AddCell(emptyTableCell);


                    foreach (var item in inventoryQuery.OrderByDescending(x => x.MarginCY))
                    {
                        if (item.InvDaysCY > item.InvDaysPY && item.InvDaysPY > 0)
                            inventoryTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 153);
                        else
                            inventoryTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                        inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        inventoryTable.AddCell(new Phrase(cont++.ToString("N0"), font10));

                        inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        inventoryTable.AddCell(new Phrase(item.Code, font10));
                        inventoryTable.AddCell(new Phrase(item.Name, font10));
                        inventoryTable.AddCell(new Phrase(item.Brand, font10));

                        inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        inventoryTable.AddCell(new Phrase(item.InventoryCY.ToString("C2"), font10));
                        inventoryTable.AddCell(new Phrase(item.InvDaysCY.ToString("N0"), font10));
                        inventoryTable.AddCell(new Phrase(item.InventoryPY.ToString("C2"), font10));
                        inventoryTable.AddCell(new Phrase(item.InvDaysPY.ToString("N0"), font10));
                        inventoryTable.AddCell(new Phrase(item.InventoryGrowth.ToString("P0"), font10));
                        inventoryTable.AddCell(new Phrase(item.InvDaysGrowth.ToString("P0"), font10));
                    }

                    document.Add(inventoryTable);
                }
                #endregion

                #region %GIM by SKU
                if (setup.DynamicsBrand || setup.DynamicsManufacturer)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "%GIM by SKU";
                    ((PageEvent)writer.PageEvent).SubTitleSecondLine = "CY vs. PY";
                    document.NewPage();

                    var marginQuery = from item in paretoItemsWithPY
                                      where !item.IsDeletedRangeReview
                                      group item by new { Code = item.Code, Name = item.Name, Brand = item.Brand.ToUpper() } into g
                                      select new
                                      {
                                          Code = g.Key.Code,
                                          Name = g.Key.Name,
                                          Brand = g.Key.Brand,
                                          MarginCY = g.Where(x => !x.IsPriorYear).Sum(x => x.GM),
                                          MarginPercCY = g.Where(x => !x.IsPriorYear).Sum(x => x.GMPercent),
                                          MarginPercPY = g.Where(x => x.IsPriorYear).Sum(x => x.GMPercent)
                                      };

                    var marginFinalQuery = from item in marginQuery
                                           select new
                                           {
                                               Code = item.Code,
                                               Name = item.Name,
                                               Brand = item.Brand,
                                               MarginCY = item.MarginCY,
                                               MarginPercCY = item.MarginPercCY,
                                               MarginPercPY = item.MarginPercPY,
                                               MarginGrowth = item.MarginPercPY != 0 ? item.MarginPercCY / item.MarginPercPY - 1 : 1
                                           };

                    PdfPTable gimTable = new PdfPTable(new float[] { 2, 5, 16, 8, 5, 5, 5, });
                    gimTable.WidthPercentage = 95;
                    gimTable.HeaderRows = 7;
                    gimTable.FooterRows = 3;
                    gimTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                    emptyTableCell.Colspan = 7;

                    greyRow = new PdfPCell(new Phrase("The products highlighted decreased their % GIM vs. PY.", font10));
                    greyRow.BackgroundColor = new BaseColor(216, 216, 216);
                    greyRow.Colspan = 7;
                    greyRow.Border = PdfPCell.NO_BORDER;
                    greyRow.Padding = 10;

                    gimTable.AddCell(emptyTableCell);
                    gimTable.AddCell(greyRow);
                    gimTable.AddCell(emptyTableCell);

                    gimTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                    gimTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    gimTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    gimTable.AddCell(new Phrase("#", font10));
                    gimTable.AddCell(new Phrase("Article Nº", font10));
                    gimTable.AddCell(new Phrase("Description", font10));
                    gimTable.AddCell(new Phrase("Brand", font10));
                    gimTable.DefaultCell.BackgroundColor = new BaseColor(242, 221, 220);
                    gimTable.AddCell(new Phrase("% GIM CY", font10));
                    gimTable.DefaultCell.BackgroundColor = new BaseColor(101, 101, 152);
                    gimTable.AddCell(new Phrase("% GIM PY", font10));
                    gimTable.DefaultCell.BackgroundColor = new BaseColor(178, 161, 199);
                    gimTable.AddCell(new Phrase("% GIM CY vs. PY", font10));

                    gimTable.AddCell(emptyTableCell);
                    gimTable.AddCell(emptyTableCell);
                    gimTable.AddCell(emptyTableCell);

                    cont = 1;
                    gimTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                    foreach (var item in marginFinalQuery.OrderByDescending(x => x.MarginCY))
                    {
                        if (item.MarginGrowth < 0)
                            gimTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 153);
                        else
                            gimTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                        gimTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        gimTable.AddCell(new Phrase(cont++.ToString("N0"), font10));

                        gimTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        gimTable.AddCell(new Phrase(item.Code, font10));
                        gimTable.AddCell(new Phrase(item.Name, font10));
                        gimTable.AddCell(new Phrase(item.Brand, font10));

                        gimTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        gimTable.AddCell(new Phrase(item.MarginPercCY.ToString("P1"), font10));
                        gimTable.AddCell(new Phrase(item.MarginPercPY.ToString("P1"), font10));
                        gimTable.AddCell(new Phrase(item.MarginGrowth.ToString("P1"), font10));
                    }

                    document.Add(gimTable);
                }
                #endregion

                #region Profitability per SKU

                ((PageEvent)writer.PageEvent).Title = "Appendix";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Profitability per SKU";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                document.NewPage();


                PdfPTable profitabilityTable = new PdfPTable(new float[] { 2, 4, 16, 8, 8, 6, 4, 6 });
                profitabilityTable.WidthPercentage = 90;
                profitabilityTable.HeaderRows = 7;
                profitabilityTable.FooterRows = 3;
                profitabilityTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                emptyTableCell.Colspan = 8;
                emptyTableCell.Border = PdfPCell.NO_BORDER;

                decimal avgProf = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.GM) / paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.Units);
                int countLowerProfSkus = paretoItems.Where(x => !x.IsDeletedRangeReview).Count(x => x.GMPerSKU < avgProf);

                greyRow = new PdfPCell(new Phrase(string.Format("{0} SKUs have a lower profitability per unit than the average ({1}).", countLowerProfSkus, avgProf.ToString("C2")), font10));
                greyRow.BackgroundColor = new BaseColor(216, 216, 216);
                greyRow.Colspan = 8;
                greyRow.Border = PdfPCell.NO_BORDER;
                greyRow.Padding = 10;

                profitabilityTable.AddCell(emptyTableCell);
                profitabilityTable.AddCell(greyRow);
                profitabilityTable.AddCell(emptyTableCell);

                profitabilityTable.DefaultCell.BackgroundColor = new BaseColor(255, 0, 102);
                profitabilityTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                profitabilityTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                profitabilityTable.AddCell(new Phrase("#", font10white));
                profitabilityTable.AddCell(new Phrase("Article Nº", font10white));
                profitabilityTable.AddCell(new Phrase("Description", font10white));
                profitabilityTable.AddCell(new Phrase("Subcategory", font10white));
                profitabilityTable.AddCell(new Phrase("Brand", font10white));
                profitabilityTable.AddCell(new Phrase("Avg. Price", font10white));
                profitabilityTable.AddCell(new Phrase("% GIM", font10white));
                profitabilityTable.AddCell(new Phrase(string.Format("Margin({0}) per SKU", currencySymbol), font10white));

                profitabilityTable.AddCell(emptyTableCell);
                profitabilityTable.AddCell(emptyTableCell);
                profitabilityTable.AddCell(emptyTableCell);

                profitabilityTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                foreach (var item in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.GMPerSKU))
                {
                    if (item.GMPerSKU < avgProf)
                        profitabilityTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 204);
                    else
                        profitabilityTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                    profitabilityTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    profitabilityTable.AddCell(new Phrase(item.Ranking.ToString("N0"), font10));

                    profitabilityTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    profitabilityTable.AddCell(new Phrase(item.Code, font10));
                    profitabilityTable.AddCell(new Phrase(item.Name, font10));
                    profitabilityTable.AddCell(new Phrase(item.Subcategory, font10));
                    profitabilityTable.AddCell(new Phrase(item.Brand.ToUpper(), font10));

                    profitabilityTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    profitabilityTable.AddCell(new Phrase(item.AveragePrice.ToString("C2"), font10));
                    profitabilityTable.AddCell(new Phrase(item.GMPercent.ToString("P1"), font10));
                    profitabilityTable.AddCell(new Phrase(item.GMPerSKU.ToString("C2"), font10));
                }

                document.Add(profitabilityTable);

                #endregion

                #region Exhibition Space by SKU
                if (setup.Space)
                {
                    ((PageEvent)writer.PageEvent).Title = "Appendix";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Exhibition Space by SKU";
                    document.NewPage();


                    PdfPTable spacesTable = new PdfPTable(new float[] { 2, 6, 16, 6, 4, 4, 4, 4, 4 });
                    spacesTable.WidthPercentage = 85;
                    spacesTable.HeaderRows = 8;
                    spacesTable.FooterRows = 3;
                    spacesTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                    emptyTableCell.Colspan = 9;


                    greyRow = new PdfPCell(new Phrase("Products highlighted in green have more than 1% gap in sales-space performance.", font10));
                    greyRow.BackgroundColor = new BaseColor(216, 216, 216);
                    greyRow.Colspan = 9;
                    greyRow.Border = PdfPCell.NO_BORDER;
                    greyRow.Padding = 5;

                    spacesTable.AddCell(emptyTableCell);
                    spacesTable.AddCell(greyRow);
                    greyRow.Phrase = new Phrase("Products highlighted in red occupy more than 1 facing within the exhibition and are over-spaced by -1% or more.", font10);
                    spacesTable.AddCell(greyRow);
                    spacesTable.AddCell(emptyTableCell);

                    spacesTable.DefaultCell.BackgroundColor = new BaseColor(204, 204, 255);
                    spacesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    spacesTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    spacesTable.AddCell(new Phrase("#", font10white));
                    spacesTable.AddCell(new Phrase("Article Nº", font10white));
                    spacesTable.AddCell(new Phrase("Description", font10white));
                    spacesTable.DefaultCell.BackgroundColor = new BaseColor(83, 142, 213);
                    spacesTable.AddCell(new Phrase("Sales " + currencySymbol, font10white));
                    spacesTable.AddCell(new Phrase("% Sales", font10white));
                    spacesTable.AddCell(new Phrase("Space (mt)", font10white));
                    spacesTable.AddCell(new Phrase("% Space", font10white));
                    spacesTable.AddCell(new Phrase("Sales % vs. Space %", font10white));
                    spacesTable.AddCell(new Phrase("Facings", font10white));

                    spacesTable.AddCell(emptyTableCell);
                    spacesTable.AddCell(emptyTableCell);
                    spacesTable.AddCell(emptyTableCell);

                    var spaceQuery = from item in paretoItems
                                     where !item.IsDeletedRangeReview
                                     select new
                                     {
                                         Ranking = item.Ranking,
                                         Code = item.Code,
                                         Name = item.Name,
                                         Sales = item.Sales,
                                         SalesShare = totalSales != 0 ? item.Sales / totalSales : 0,
                                         LinearSpace = item.LinearSpace,
                                         LinearSpaceShare = totalSpace != 0 ? item.LinearSpace / totalSpace : 0,
                                         SalesVsSpace = totalSales != 0 && totalSpace != 0 ? (item.Sales / totalSales) - (item.LinearSpace / totalSpace) : 0,
                                         Facings = item.Facings
                                     };

                    spacesTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                    foreach (var item in spaceQuery.OrderBy(x => x.Ranking))
                    {
                        if (item.SalesVsSpace > 0.01m)
                            spacesTable.DefaultCell.BackgroundColor = new BaseColor(204, 255, 204);
                        else if (item.SalesVsSpace < -0.01m && item.Facings > 1)
                            spacesTable.DefaultCell.BackgroundColor = new BaseColor(255, 153, 153);
                        else
                            spacesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                        spacesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        spacesTable.AddCell(new Phrase(item.Ranking.ToString("N0"), font10));

                        spacesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        spacesTable.AddCell(new Phrase(item.Code, font10));
                        spacesTable.AddCell(new Phrase(item.Name, font10));

                        spacesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        spacesTable.AddCell(new Phrase(item.Sales.ToString("C2"), font10));
                        spacesTable.AddCell(new Phrase(item.SalesShare.ToString("P1"), font10));
                        spacesTable.AddCell(new Phrase(item.LinearSpace.ToString("N2"), font10));
                        spacesTable.AddCell(new Phrase(item.LinearSpaceShare.ToString("P1"), font10));
                        spacesTable.AddCell(new Phrase(item.SalesVsSpace.ToString("P1"), font10));
                        spacesTable.AddCell(new Phrase(item.Facings.ToString("N0"), font10));
                    }

                    document.Add(spacesTable);
                }

                #endregion
                #endregion

                // step 5
                document.Close();

                return stream.ToArray();

            }

            return null;
        }

        public static byte[] GenerateExecutiveSummaryReport(int rangeReviewId)
        {
            //return QuickTest(rangeReviewId, 0);

            #region Report Configuration

            RangeReview rangeReview = RangeReviewDomain.GetById(rangeReviewId, true);
            Country country = CountriesDomain.GetById(rangeReview.CountryId);

            //Culture
            if (country.Code == "US" || country.Code == "CA")
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            }

            var targetCurrency = CurrenciesRepository.Select(x => x.Id == rangeReview.TargetCurrencyId).SingleOrDefault();

            NumberFormatInfo numberFormatInfo = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
            string currencySymbol = targetCurrency.CurrencySymbol;
            numberFormatInfo.CurrencySymbol = country.CurrencySymbol;
            numberFormatInfo.CurrencyPositivePattern = 2;
            numberFormatInfo.CurrencyNegativePattern = 12;
            if (numberFormatInfo.CurrencyDecimalSeparator == ",")
            {
                numberFormatInfo.CurrencyGroupSeparator = ".";
            }
            else
            {
                numberFormatInfo.CurrencyGroupSeparator = ",";
            }
            System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat = numberFormatInfo;

            List<GeneralComment> generalComments = GeneralCommentsRepository.Select(x => x.RangeReviewId == rangeReview.Id && x.ReportType == ReportType.ExecutiveSummary.ToString())
                                                                            .ConvertAll<GeneralComment>(row => new GeneralComment(row));


            BaseFont Calibri = ReportsHelper.GetCalibriOrDefault();

            Font font16 = new Font(Calibri, 16, Font.NORMAL, BaseColor.BLACK);
            Font font16bold = new Font(Calibri, 16, Font.BOLD, BaseColor.BLACK);
            Font font14 = new Font(Calibri, 14, Font.NORMAL, BaseColor.BLACK);
            Font font14bold = new Font(Calibri, 14, Font.BOLD, BaseColor.BLACK);
            Font font30 = new Font(Calibri, 30, Font.NORMAL, BaseColor.BLUE);
            Font font20 = new Font(Calibri, 20, Font.NORMAL, BaseColor.BLUE);
            Font font13blue = new Font(Calibri, 13, Font.BOLD, new BaseColor(31, 72, 124));
            Font font13 = new Font(Calibri, 13, Font.NORMAL, BaseColor.BLACK);
            Font font11bold = new Font(Calibri, 11, Font.BOLD, BaseColor.BLACK);
            Font font11 = new Font(Calibri, 11, Font.NORMAL, BaseColor.BLACK);
            Font font12bold = new Font(Calibri, 11, Font.BOLD, BaseColor.BLACK);
            Font font12 = new Font(Calibri, 12, Font.NORMAL, BaseColor.BLACK);
            Font font13bold = new Font(Calibri, 13, Font.BOLD, BaseColor.BLACK);
            Font font10bold = new Font(Calibri, 10, Font.BOLD, BaseColor.BLACK);
            Font font10 = new Font(Calibri, 10, Font.NORMAL, BaseColor.BLACK);
            Font font10boldWhite = new Font(Calibri, 10, Font.BOLD, BaseColor.WHITE);
            Font font10White = new Font(Calibri, 10, Font.NORMAL, BaseColor.WHITE);
            Font font10boldRed = new Font(Calibri, 10, Font.BOLD, BaseColor.RED);
            Font font9bold = new Font(Calibri, 9, Font.BOLD, BaseColor.BLACK);
            Font font9 = new Font(Calibri, 9, Font.NORMAL, BaseColor.BLACK);
            Font font7 = new Font(Calibri, 7, Font.NORMAL, BaseColor.BLACK);

            var paretoRowsWithPY = ReportsRepository.GetSalesCategoryComparisonPareto(rangeReviewId, 0, true, 0, 1).Where(x => !x.IsDeletedPerformance).ToList();
            List<SalesCategoryComparisonPareto> paretoItemsWithPY = paretoRowsWithPY.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

            var paretoRows = paretoRowsWithPY.Where(x => !x.IsPriorYear).ToList();
            List<SalesCategoryComparisonPareto> paretoItems = paretoRows.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

            var paretoRowsWithPYSS = ReportsRepository.GetSalesCategoryComparisonPareto(rangeReviewId, 0, true, 0, 2).Where(x => !x.IsDeletedPerformance).ToList();
            List<SalesCategoryComparisonPareto> paretoItemsWithPYSS = paretoRowsWithPYSS.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));

            int totalDelistedSKUs = paretoItems.Where(x => x.Delist && !x.IsDeletedRangeReview).Count();

            //Same Store
            var totalSalesSameStore = (from s in paretoItemsWithPYSS
                                       group s by new { s.IsPriorYear } into g
                                       select new SalesCategoryComparison
                                       {
                                           Title = rangeReview.Title,
                                           IsPriorYear = g.Key.IsPriorYear,
                                           Units = g.Sum(x => x.Units),
                                           Sales = g.Sum(x => x.Sales),
                                           GM = g.Sum(x => x.GM),
                                           UnitsShare = 1m,
                                           SalesShare = 1m,
                                           GMShare = 1m,
                                           PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                           ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                           InventoryCost = g.Sum(x => x.InventoryCost),
                                           LinearSpace = g.Sum(x => x.LinearSpace),
                                           SKUs = g.Count()
                                       }).ToList();

            var totalSalesAverageStore = (from s in paretoItemsWithPY
                                          where !s.IsDeletedRangeReview
                                          group s by new { s.IsPriorYear } into g
                                          select new SalesCategoryComparison
                                          {
                                              Title = rangeReview.Title,
                                              IsPriorYear = g.Key.IsPriorYear,
                                              Units = g.Sum(x => x.Units),
                                              Sales = g.Sum(x => x.Sales),
                                              GM = g.Sum(x => x.GM),
                                              UnitsShare = 1m,
                                              SalesShare = 1m,
                                              GMShare = 1m,
                                              PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                              ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                              InventoryCost = g.Sum(x => x.InventoryCost),
                                              LinearSpace = g.Sum(x => x.LinearSpace),
                                              SKUs = g.Count()
                                          }).ToList();

            var totalSalesAverageStoreDelist = (from s in paretoItemsWithPY
                                                where !s.IsDeletedRangeReview && s.Delist
                                                group s by new { s.IsPriorYear } into g
                                                select new SalesCategoryComparison
                                                {
                                                    Title = rangeReview.Title,
                                                    IsPriorYear = g.Key.IsPriorYear,
                                                    Units = g.Sum(x => x.Units),
                                                    Sales = g.Sum(x => x.Sales),
                                                    GM = g.Sum(x => x.GM),
                                                    UnitsShare = 1m,
                                                    SalesShare = 1m,
                                                    GMShare = 1m,
                                                    PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                                    ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                                    InventoryCost = g.Sum(x => x.InventoryCost),
                                                    LinearSpace = g.Sum(x => x.LinearSpace),
                                                    SKUs = g.Count()
                                                }).ToList();

            //Total Pais Same Store
            var totalSaleSameStoreCY = totalSalesSameStore.Where(x => !x.IsPriorYear).SingleOrDefault();
            var totalSaleSameStorePY = totalSalesSameStore.Where(x => x.IsPriorYear).SingleOrDefault();

            //Total Pais Average Store
            var totalSaleAverageStoreCY = totalSalesAverageStore.Where(x => !x.IsPriorYear).SingleOrDefault();
            var totalSaleAverageStorePY = totalSalesAverageStore.Where(x => x.IsPriorYear).SingleOrDefault();

            //Total Pais Average Store Delist Proposal
            var totalSalesAverageStoreDelistCY = totalSalesAverageStoreDelist.Where(x => !x.IsPriorYear).SingleOrDefault();
            var totalSalesAverageStoreDelistPY = totalSalesAverageStoreDelist.Where(x => x.IsPriorYear).SingleOrDefault();

            var categorySalesSameStore = (from s in paretoItemsWithPYSS
                                          group s by new { s.IsPriorYear, s.Category, s.CategoryId } into g
                                          select new SalesCategoryComparison
                                          {
                                              Title = rangeReview.Title,
                                              Category = g.Key.Category,
                                              CategoryId = g.Key.CategoryId,
                                              IsPriorYear = g.Key.IsPriorYear,
                                              Units = g.Sum(x => x.Units),
                                              Sales = g.Sum(x => x.Sales),
                                              GM = g.Sum(x => x.GM),
                                              UnitsShare = totalSaleSameStoreCY != null && totalSaleSameStoreCY.Units != 0 ? g.Sum(x => x.Units) / totalSaleSameStoreCY.Units : 0,
                                              SalesShare = totalSaleSameStoreCY != null && totalSaleSameStoreCY.Sales != 0 ? g.Sum(x => x.Sales) / totalSaleSameStoreCY.Sales : 0,
                                              GMShare = totalSaleSameStoreCY != null && totalSaleSameStoreCY.GM != 0 ? g.Sum(x => x.GM) / totalSaleSameStoreCY.GM : 0,
                                              PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                              ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                              InventoryCost = g.Sum(x => x.InventoryCost),
                                              LinearSpace = g.Sum(x => x.LinearSpace),
                                              SKUs = g.Count()
                                          }).ToList();

            var categorySalesAverageStore = (from s in paretoItemsWithPY
                                             where !s.IsDeletedRangeReview
                                             group s by new { s.IsPriorYear, s.Category, s.CategoryId } into g
                                             select new SalesCategoryComparison
                                             {
                                                 Title = rangeReview.Title,
                                                 Category = g.Key.Category,
                                                 CategoryId = g.Key.CategoryId,
                                                 IsPriorYear = g.Key.IsPriorYear,
                                                 Units = g.Sum(x => x.Units),
                                                 Sales = g.Sum(x => x.Sales),
                                                 GM = g.Sum(x => x.GM),
                                                 UnitsShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.Units != 0 ? g.Sum(x => x.Units) / totalSaleAverageStoreCY.Units : 0,
                                                 SalesShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.Sales != 0 ? g.Sum(x => x.Sales) / totalSaleAverageStoreCY.Sales : 0,
                                                 GMShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.GM != 0 ? g.Sum(x => x.GM) / totalSaleAverageStoreCY.GM : 0,
                                                 PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                                 ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                                 InventoryCost = g.Sum(x => x.InventoryCost),
                                                 LinearSpace = g.Sum(x => x.LinearSpace),
                                                 SKUs = g.Count()
                                             }).ToList();

            var categorySalesAverageStoreDelist = (from s in paretoItemsWithPY
                                                   where !s.IsDeletedRangeReview && s.Delist
                                                   group s by new { s.IsPriorYear, s.Category, s.CategoryId } into g
                                                   select new SalesCategoryComparison
                                                   {
                                                       Title = rangeReview.Title,
                                                       Category = g.Key.Category,
                                                       CategoryId = g.Key.CategoryId,
                                                       IsPriorYear = g.Key.IsPriorYear,
                                                       Units = g.Sum(x => x.Units),
                                                       Sales = g.Sum(x => x.Sales),
                                                       GM = g.Sum(x => x.GM),
                                                       UnitsShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.Units != 0 ? g.Sum(x => x.Units) / totalSaleAverageStoreCY.Units : 0,
                                                       SalesShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.Sales != 0 ? g.Sum(x => x.Sales) / totalSaleAverageStoreCY.Sales : 0,
                                                       GMShare = totalSaleAverageStoreCY != null && totalSaleAverageStoreCY.GM != 0 ? g.Sum(x => x.GM) / totalSaleAverageStoreCY.GM : 0,
                                                       PIDiff = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.PIDiff) / g.Sum(x => x.Sales) : 0,
                                                       ChargeOffs = g.Sum(x => x.Sales) != 0 ? g.Sum(x => x.ChargeOffs) / g.Sum(x => x.Sales) : 0,
                                                       InventoryCost = g.Sum(x => x.InventoryCost),
                                                       LinearSpace = g.Sum(x => x.LinearSpace),
                                                       SKUs = g.Count()
                                                   }).ToList();




            //Total Categoria Same Store
            var categorySalesSameStoreCY = categorySalesSameStore.Where(x => !x.IsPriorYear).ToList();
            var categorySalesSameStorePY = categorySalesSameStore.Where(x => x.IsPriorYear).ToList();

            //Calculo el skus80SalesPerc porque lo voy a usar en los Benchmarks
            decimal paretoAcum = 0;
            decimal paretoPrevAcum = 0;
            decimal skus80Sales = 0;
            int skusBottom5 = 0;

            //Loopeo solo los skus activos.
            foreach (var paretoItem in paretoItems.Where(x => !x.IsDeletedRangeReview).OrderByDescending(x => x.Sales))
            {
                paretoPrevAcum = paretoAcum;
                paretoAcum += paretoItem.Sales / totalSaleAverageStoreCY.Sales;

                if (paretoPrevAcum <= 0.8m)
                {
                    skus80Sales++;
                }
                else if (paretoPrevAcum >= 0.95m)
                {
                    skusBottom5++;
                }
            }

            decimal skus80SalesPercTotal = totalSaleAverageStoreCY.SKUs != 0 ? skus80Sales / totalSaleAverageStoreCY.SKUs : 0;


            #endregion


            if (totalSaleSameStoreCY != null)
            {
                //Preparo el documento PDF
                Document document = new Document(PageSize.LETTER.Rotate(), 0, 0, 0, 0);
                MemoryStream stream = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new PageEvent();
                ((PageEvent)writer.PageEvent).GeneralComments = generalComments;
                document.Open();

                #region Front page

                document.NewPage();

                PdfPTable layoutTable = new PdfPTable(new float[] { 50f, 50f });
                layoutTable.WidthPercentage = 100;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.DefaultCell.Padding = 0;

                //Imagen de caratula.
                string path = Path.Combine(ConfigurationManager.AppSettings["ImportersPath"], country.Code, rangeReview.Title, Constants.ImportSettings.ReportsFronPages, country.Code + ".png");
                if (!File.Exists(path))
                {
                    throw new FaultException<ARRExceptionDetail>(new ARRExceptionDetail("Debe agregar una imagen para la caratula en la ruta " + path, ExceptionSeverity.Validation));
                }

                Image img = iTextSharp.text.Image.GetInstance(path);
                img.ScaleToFit(document.PageSize.Width / 2, document.PageSize.Height);
                img.ScaleToFitLineWhenOverflow = true;
                layoutTable.AddCell(img);


                //Tabla para layout de la derecha.
                PdfPTable rightLayout = new PdfPTable(new float[] { 100f });
                rightLayout.WidthPercentage = 100;
                rightLayout.DefaultCell.FixedHeight = document.PageSize.Height / 3;

                Font frontPageFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, new BaseColor(213, 228, 199));
                Font frontPageFontSubtitles = new Font(Font.FontFamily.HELVETICA, 13, Font.BOLD, new BaseColor(213, 228, 199));

                rightLayout.DefaultCell.BackgroundColor = new BaseColor(50, 75, 105);
                rightLayout.DefaultCell.PaddingLeft = 50;
                rightLayout.DefaultCell.PaddingTop = 60;

                Paragraph para1 = new Paragraph();
                para1.Font = frontPageFont;
                para1.Add("Category Management  \n");
                para1.Add("Product Range Analysis \n\n");
                Paragraph para1Subtitle = new Paragraph();
                para1Subtitle.Font = frontPageFontSubtitles;
                para1Subtitle.Add(rangeReview.ReportDate.ToString("MMMM yyyy", new CultureInfo("EN-us")));
                para1.Add(para1Subtitle);
                rightLayout.DefaultCell.Border = PdfPCell.NO_BORDER;
                rightLayout.DefaultCell.BorderWidth = 0;
                rightLayout.AddCell(para1);

                Paragraph para2 = new Paragraph();
                para2.Font = frontPageFont;
                para2.Add("RANGE REVIEW SUMMARY");
                rightLayout.DefaultCell.BackgroundColor = new BaseColor(70, 102, 140);
                rightLayout.AddCell(para2);

                Paragraph para3 = new Paragraph();
                para3.Font = frontPageFont;
                para3.Add(rangeReview.Title.ToUpper());
                rightLayout.DefaultCell.BackgroundColor = new BaseColor(107, 132, 163);
                rightLayout.AddCell(para3);
                layoutTable.AddCell(rightLayout);

                document.Add(layoutTable);

                #endregion

                #region Product Range Analysis Highlights

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                Paragraph caratula2 = new Paragraph();
                caratula2.SpacingBefore = 180f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.Add(new Phrase("Product Range Analysis Highlights", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Performance and Benchmarking - Same Store

                #region Titulo de la pagina y Headers de la tabla

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Performance and Benchmarking - Same Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();


                Font font = new Font(Calibri, 10, Font.NORMAL, BaseColor.BLACK);
                Font fontRed = new Font(Calibri, 10, Font.NORMAL, BaseColor.RED);

                document.Add(new Paragraph(" "));

                //Benchmarks
                //Traigo los datos de RangeReviewBenchmarks, hasta 3 columnas para la primer pagina.
                SalesCategoryComparison saleColumn1 = null;
                SalesCategoryComparison saleColumn2 = null;
                SalesCategoryComparison saleColumn3 = null;
                var benchmarks = RangeReviewBenchmarksRepository.Select(x => x.RangeReviewSourceId == rangeReviewId).OrderBy(x => x.ColumnNumber).ToList();
                int countColumns = 0;
                foreach (var benchmark in benchmarks)
                {
                    List<SalesCategoryComparisonRow> columnRows;
                    if (benchmark.HistoryGroupId.HasValue)
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparisonHistoryBenchmark(rangeReviewId, 0, benchmark.HistoryGroupId.Value, false, true).ToList();
                    }
                    else
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparison(rangeReviewId, 0, benchmark.StoreId, benchmark.StoreGroupId).ToList();
                    }

                    if (columnRows.Count > 0)
                    {
                        List<SalesCategoryComparison> salesColumn = columnRows.ConvertAll<SalesCategoryComparison>(c => new SalesCategoryComparison(c));
                        switch (countColumns)
                        {
                            case 0:
                                saleColumn1 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                            case 1:
                                saleColumn2 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                            case 2:
                                saleColumn3 = salesColumn.Where(x => !x.IsPriorYear).First();
                                break;
                        }
                        countColumns++;
                    }
                }

                countColumns = (countColumns * 2) + 2;
                if (totalSaleSameStorePY != null)
                {
                    countColumns = countColumns + 2;
                }

                //Genero una tabla con datos
                float[] columnRelativeWidths = new float[countColumns];
                float relativeWidth = 100f / countColumns;
                for (int i = 0; i < countColumns; i++)
                {
                    if (i == 0)
                    {
                        columnRelativeWidths.SetValue(relativeWidth * 2, i);
                    }
                    else
                    {
                        columnRelativeWidths.SetValue(relativeWidth, i);
                    }
                }

                PdfPTable dataTable = new PdfPTable(columnRelativeWidths);
                //dataTable.HorizontalAlignment = Element.ALIGN_CENTER;
                dataTable.WidthPercentage = countColumns < 10 ? countColumns * 10 : 95f;

                dataTable.DefaultCell.BackgroundColor = new BaseColor(184, 204, 228);
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                dataTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                dataTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;

                dataTable.AddCell(new Phrase("TOTAL STORE", font));
                dataTable.AddCell(new Phrase(rangeReview.Title, font));

                //Columnas Benchmark
                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(rangeReview.Title + " PY", font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.Name, font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.Name, font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.Name, font));
                }

                //Columnas comparativas
                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase("Comparison vs. " + rangeReview.Title + " PY", font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase("Comparison vs. " + saleColumn1.Name, font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase("Comparison vs. " + saleColumn2.Name, font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase("Comparison vs. " + saleColumn3.Name, font));
                }

                #endregion

                #region Sales, Margins, Units

                //Celda para datos
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                //Fila en blanco
                PdfPCell emptyTableCell = new PdfPCell(new Phrase("  "));
                emptyTableCell.Colspan = countColumns;
                emptyTableCell.Border = PdfPCell.NO_BORDER;

                //Benchmark Sales                
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Sales", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.Sales.ToString("C0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.Sales.ToString("C0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.Sales.ToString("C0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.Sales.ToString("C0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.Sales.ToString("C0"), font));
                }

                //Comparativas Sales
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.Sales != 0 ? totalSaleSameStoreCY.Sales / totalSaleSameStorePY.Sales - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.Sales != 0 ? totalSaleSameStoreCY.Sales / saleColumn1.Sales - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.Sales != 0 ? totalSaleSameStoreCY.Sales / saleColumn2.Sales - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.Sales != 0 ? totalSaleSameStoreCY.Sales / saleColumn3.Sales - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark GI Margin
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("GI Margin", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.GM.ToString("C0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.GM.ToString("C0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.GM.ToString("C0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.GM.ToString("C0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.GM.ToString("C0"), font));
                }

                //Comparativas GI Margin
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.GM != 0 ? (totalSaleSameStoreCY.GM / totalSaleSameStorePY.GM - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.GM != 0 ? (totalSaleSameStoreCY.GM / saleColumn1.GM - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.GM != 0 ? (totalSaleSameStoreCY.GM / saleColumn2.GM - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.GM != 0 ? (totalSaleSameStoreCY.GM / saleColumn3.GM - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark GI Margin %
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("GI Margin %", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.GMPercent.ToString("P1"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.GMPercent.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.GMPercent.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.GMPercent.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.GMPercent.ToString("P1"), font));
                }

                //Comparativas GI Margin %
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.GMPercent != 0 ? totalSaleSameStoreCY.GMPercent / totalSaleSameStorePY.GMPercent - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.GMPercent != 0 ? totalSaleSameStoreCY.GMPercent / saleColumn1.GMPercent - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.GMPercent != 0 ? totalSaleSameStoreCY.GMPercent / saleColumn2.GMPercent - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.GMPercent != 0 ? totalSaleSameStoreCY.GMPercent / saleColumn3.GMPercent - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark Units
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Sales Units", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.Units.ToString("N0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.Units.ToString("N0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.Units.ToString("N0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.Units.ToString("N0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.Units.ToString("N0"), font));
                }

                //Comparativos Units
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.Units != 0 ? totalSaleSameStoreCY.Units / totalSaleSameStorePY.Units - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.Units != 0 ? totalSaleSameStoreCY.Units / saleColumn1.Units - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.Units != 0 ? totalSaleSameStoreCY.Units / saleColumn2.Units - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.Units != 0 ? totalSaleSameStoreCY.Units / saleColumn3.Units - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Agrego una fila vacia y sin bordes
                dataTable.AddCell(emptyTableCell);
                #endregion

                #region Inventory

                //Benchmark Inventories
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Inventory", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.InventoryCost.ToString("C0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.InventoryCost.ToString("C0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.InventoryCost.ToString("C0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.InventoryCost.ToString("C0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.InventoryCost.ToString("C0"), font));
                }

                //Comparativos Inventories
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / totalSaleSameStorePY.InventoryCost - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / saleColumn1.InventoryCost - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / saleColumn2.InventoryCost - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / saleColumn3.InventoryCost - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark Inv Days
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Inv Days", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.InvDays.ToString("N0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.InvDays.ToString("N0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.InvDays.ToString("N0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.InvDays.ToString("N0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.InvDays.ToString("N0"), font));
                }

                //Comparativos Inv Days
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.InvDays != 0 ? totalSaleSameStoreCY.InvDays / totalSaleSameStorePY.InvDays - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.InvDays != 0 ? totalSaleSameStoreCY.InvDays / saleColumn1.InvDays - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.InvDays != 0 ? totalSaleSameStoreCY.InvDays / saleColumn2.InvDays - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.InvDays != 0 ? totalSaleSameStoreCY.InvDays / saleColumn3.InvDays - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark Annual Stock Turns
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Annual Stock Turn", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.AnnualStockTurn.ToString("N0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.AnnualStockTurn.ToString("N0"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.AnnualStockTurn.ToString("N0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.AnnualStockTurn.ToString("N0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.AnnualStockTurn.ToString("N0"), font));
                }

                //Comparativos Annual Stock Turns
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.AnnualStockTurn != 0 ? totalSaleSameStoreCY.AnnualStockTurn / totalSaleSameStorePY.AnnualStockTurn - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.AnnualStockTurn != 0 ? totalSaleSameStoreCY.AnnualStockTurn / saleColumn1.AnnualStockTurn - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.AnnualStockTurn != 0 ? totalSaleSameStoreCY.AnnualStockTurn / saleColumn2.AnnualStockTurn - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.AnnualStockTurn != 0 ? totalSaleSameStoreCY.AnnualStockTurn / saleColumn3.AnnualStockTurn - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark GMROI
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("GMROI", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.GMROI.ToString("N2"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.GMROI.ToString("N2"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.GMROI.ToString("N2"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.GMROI.ToString("N2"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.GMROI.ToString("N2"), font));
                }

                //Comparativos GMROI
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.GMROI != 0 ? totalSaleSameStoreCY.GMROI / totalSaleSameStorePY.GMROI - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.GMROI != 0 ? totalSaleSameStoreCY.GMROI / saleColumn1.GMROI - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.GMROI != 0 ? totalSaleSameStoreCY.GMROI / saleColumn2.GMROI - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.GMROI != 0 ? totalSaleSameStoreCY.GMROI / saleColumn3.GMROI - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Agrego una fila vacia y sin bordes
                dataTable.AddCell(emptyTableCell);

                #endregion

                #region Spaces

                //Benchmark Spaces
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Space (mt.)", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.LinearSpace.ToString("N2"), font));

                //Si tengo Range Review Anterior traigo la data del RR anterior
                int totalSKUsPRR = 0;
                decimal skus80PRR = 0;
                decimal? totalSpacePRR = null;
                decimal? totalSalesOverSpacePRR = null;
                decimal? totalGMROSPRR = null;
                if (rangeReview.PYHistoryId.HasValue)
                {
                    var prrRows = HistoryDetailsRepository.Select(x => x.HistoryId == rangeReview.PYHistoryId.Value && x.Category == "TOTAL STORE");
                    var prr = prrRows.ConvertAll<HistoryDetail>(c => new HistoryDetail(c)).FirstOrDefault();
                    if (prr != null)
                    {
                        totalSpacePRR = prr.Space;
                        totalSalesOverSpacePRR = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? totalSaleSameStorePY.Sales / totalSpacePRR : null;
                        totalGMROSPRR = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? totalSaleSameStorePY.GM / totalSpacePRR : null;
                        totalSKUsPRR = prr.SKUsWithSales.HasValue ? prr.SKUsWithSales.Value : 0;
                        skus80PRR = prr.Sales80.HasValue && prr.SKUsWithSales.HasValue && prr.SKUsWithSales.Value != 0 ? (decimal)prr.Sales80.Value / prr.SKUsWithSales.Value : 0;
                    }
                }

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? totalSpacePRR.Value.ToString("N2") : string.Empty, font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.LinearSpace.ToString("N2"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.LinearSpace.ToString("N2"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.LinearSpace.ToString("N2"), font));
                }

                //Comparativos Spaces
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSpacePRR.HasValue && totalSpacePRR.Value != 0 ? totalSaleSameStoreCY.LinearSpace / totalSpacePRR.Value - 1 : 1;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.LinearSpace != 0 ? totalSaleSameStoreCY.LinearSpace / saleColumn1.LinearSpace - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.LinearSpace != 0 ? totalSaleSameStoreCY.LinearSpace / saleColumn2.LinearSpace - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.LinearSpace != 0 ? totalSaleSameStoreCY.LinearSpace / saleColumn3.LinearSpace - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark Sales / Linear mt
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Sales / Linear mt", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.SalesOverLinearMt.ToString("C0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSalesOverSpacePRR.HasValue ? totalSalesOverSpacePRR.Value.ToString("C0") : string.Empty, font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.SalesOverLinearMt.ToString("C0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.SalesOverLinearMt.ToString("C0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.SalesOverLinearMt.ToString("C0"), font));
                }

                //Comparativos Sales / Linear mt
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSalesOverSpacePRR.HasValue && totalSalesOverSpacePRR.Value != 0 ? totalSaleSameStoreCY.SalesOverLinearMt / totalSalesOverSpacePRR.Value - 1 : 1;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.SalesOverLinearMt != 0 ? (totalSaleSameStoreCY.SalesOverLinearMt / saleColumn1.SalesOverLinearMt - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.SalesOverLinearMt != 0 ? (totalSaleSameStoreCY.SalesOverLinearMt / saleColumn2.SalesOverLinearMt - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.SalesOverLinearMt != 0 ? (totalSaleSameStoreCY.SalesOverLinearMt / saleColumn3.SalesOverLinearMt - 1) : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark GMROS
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("GMROS", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.GMROS.ToString("C0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalGMROSPRR.HasValue ? totalGMROSPRR.Value.ToString("C0") : string.Empty, font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.GMROS.ToString("C0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.GMROS.ToString("C0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.GMROS.ToString("C0"), font));
                }

                //Comparativos GMROS
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalGMROSPRR.HasValue && totalGMROSPRR.Value != 0 ? totalSaleSameStoreCY.GMROS / totalGMROSPRR.Value - 1 : 1;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.GMROS != 0 ? totalSaleSameStoreCY.GMROS / saleColumn1.GMROS - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.GMROS != 0 ? totalSaleSameStoreCY.GMROS / saleColumn2.GMROS - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.GMROS != 0 ? totalSaleSameStoreCY.GMROS / saleColumn3.GMROS - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Agrego una fila vacia y sin bordes
                dataTable.AddCell(emptyTableCell);

                #endregion

                #region SKUs
                //SKUs
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("SKUs", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleAverageStoreCY.SKUs.ToString("N0"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSKUsPRR != 0 ? totalSKUsPRR.ToString("N0") : string.Empty, font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.SKUs.ToString("N0"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.SKUs.ToString("N0"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.SKUs.ToString("N0"), font));
                }

                //Comparativos SKUs
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSKUsPRR != 0 ? (decimal)totalSaleAverageStoreCY.SKUs / totalSKUsPRR - 1 : 1;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.SKUs != 0 ? (decimal)totalSaleAverageStoreCY.SKUs / saleColumn1.SKUs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.SKUs != 0 ? (decimal)totalSaleAverageStoreCY.SKUs / saleColumn2.SKUs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.SKUs != 0 ? (decimal)totalSaleAverageStoreCY.SKUs / saleColumn3.SKUs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //SKUs with 80% Sales
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("SKUs with 80% of sales", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(skus80SalesPercTotal.ToString("P1"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(skus80PRR != 0 ? skus80PRR.ToString("P1") : string.Empty, font));
                }

                //TODO: si el comparativo no es contra historico el dato Sales80 viene en 0
                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.Sales80 != 0 ? ((decimal)saleColumn1.Sales80 / saleColumn1.SKUs).ToString("P1") : "0 %", font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.Sales80 != 0 ? ((decimal)saleColumn2.Sales80 / saleColumn2.SKUs).ToString("P1") : "0 %", font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.Sales80 != 0 ? ((decimal)saleColumn3.Sales80 / saleColumn3.SKUs).ToString("P1") : "0 %", font));
                }

                //Comparativos SKUs with 80% Sales
                if (totalSaleSameStorePY != null)
                {
                    decimal result = skus80PRR != 0 ? skus80SalesPercTotal / skus80PRR - 1 : 1;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.Sales80 != 0 ? skus80SalesPercTotal / ((decimal)saleColumn1.Sales80 / saleColumn1.SKUs) - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.Sales80 != 0 ? skus80SalesPercTotal / ((decimal)saleColumn2.Sales80 / saleColumn2.SKUs) - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.Sales80 != 0 ? skus80SalesPercTotal / ((decimal)saleColumn3.Sales80 / saleColumn3.SKUs) - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Agrego una fila vacia y sin bordes
                dataTable.AddCell(emptyTableCell);

                #endregion

                #region PI Differences
                //Benchmark PI Differences
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("PI Differences", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.PIDiff.ToString("P1"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.PIDiff.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.PIDiff.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.PIDiff.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.PIDiff.ToString("P1"), font));
                }


                //Comparativos PI Differences
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.PIDiff != 0 ? totalSaleSameStoreCY.PIDiff / totalSaleSameStorePY.PIDiff - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.PIDiff != 0 ? totalSaleSameStoreCY.PIDiff / saleColumn1.PIDiff - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.PIDiff != 0 ? totalSaleSameStoreCY.PIDiff / saleColumn2.PIDiff - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.PIDiff != 0 ? totalSaleSameStoreCY.PIDiff / saleColumn3.PIDiff - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark ChargeOffs
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Charge Off", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.ChargeOffs.ToString("P1"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.ChargeOffs.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.ChargeOffs.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.ChargeOffs.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.ChargeOffs.ToString("P1"), font));
                }

                //Comparativos ChargeOffs
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.ChargeOffs != 0 ? totalSaleSameStoreCY.ChargeOffs / totalSaleSameStorePY.ChargeOffs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.ChargeOffs != 0 ? totalSaleSameStoreCY.ChargeOffs / saleColumn1.ChargeOffs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.ChargeOffs != 0 ? totalSaleSameStoreCY.ChargeOffs / saleColumn2.ChargeOffs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.ChargeOffs != 0 ? totalSaleSameStoreCY.ChargeOffs / saleColumn3.ChargeOffs - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Benchmark Actual Margin
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                dataTable.AddCell(new Phrase("Actual Margin %", font));
                dataTable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                dataTable.AddCell(new Phrase(totalSaleSameStoreCY.ActualMargin.ToString("P1"), font));

                if (totalSaleSameStorePY != null)
                {
                    dataTable.AddCell(new Phrase(totalSaleSameStorePY.ActualMargin.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn1.ActualMargin.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn2.ActualMargin.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    dataTable.AddCell(new Phrase(saleColumn3.ActualMargin.ToString("P1"), font));
                }

                //Comparativos Actual Margin
                if (totalSaleSameStorePY != null)
                {
                    decimal result = totalSaleSameStorePY.ActualMargin != 0 ? totalSaleSameStoreCY.ActualMargin / totalSaleSameStorePY.ActualMargin - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn1 != null)
                {
                    decimal result = saleColumn1.ActualMargin != 0 ? totalSaleSameStoreCY.ActualMargin / saleColumn1.ActualMargin - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn2 != null)
                {
                    decimal result = saleColumn2.ActualMargin != 0 ? totalSaleSameStoreCY.ActualMargin / saleColumn2.ActualMargin - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                if (saleColumn3 != null)
                {
                    decimal result = saleColumn3.ActualMargin != 0 ? totalSaleSameStoreCY.ActualMargin / saleColumn3.ActualMargin - 1 : 0;
                    dataTable.AddCell(new Phrase(result.ToString("P1"), font));
                }

                //Agrego una fila vacia y sin bordes
                dataTable.AddCell(emptyTableCell);

                #endregion

                document.Add(dataTable);
                #endregion

                #region Sales, GI Margin and Sales Units Contribution

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sales, GI Margin and Sales Units Contribution";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable graphicsTable = new PdfPTable(new float[] { 33f, 33f, 33f });
                graphicsTable.WidthPercentage = 100f;
                PdfPCell graphicsCell;

                #region Preparo la data
                //Preparo el datasource para los 3 graficos.
                List<SalesCategoryComparison> items80Percent = new List<SalesCategoryComparison>();

                decimal acum = 0;
                int catCount = 0;
                foreach (var item in categorySalesSameStoreCY.OrderByDescending(x => x.GM))
                {
                    acum += item.GMShare;
                    catCount++;
                    if (acum < 0.8m)
                    {
                        items80Percent.Add(item);
                    }
                    else
                    {
                        break;
                    }
                }

                if (categorySalesSameStoreCY.Count() != items80Percent.Count)
                {
                    var others = from s in categorySalesSameStoreCY.OrderByDescending(x => x.GM)
                                 where !items80Percent.Contains(s)
                                 group s by s.IsPriorYear into g
                                 select new SalesCategoryComparison
                                 {
                                     Category = "Others",
                                     SalesShare = g.Sum(x => x.SalesShare),
                                     GMShare = g.Sum(x => x.GMShare),
                                     UnitsShare = g.Sum(x => x.UnitsShare)
                                 };

                    items80Percent.Add(others.SingleOrDefault());
                }

                System.Drawing.Color[] barColors = new System.Drawing.Color[]
                {
                       System.Drawing.Color.FromArgb(70, 119, 172),
                       System.Drawing.Color.FromArgb(173, 71, 68),
                       System.Drawing.Color.FromArgb(141, 169, 78),
                       System.Drawing.Color.FromArgb(115, 90, 143),
                       System.Drawing.Color.FromArgb(66, 154, 180),
                       System.Drawing.Color.FromArgb(223, 133, 61),
                       System.Drawing.Color.FromArgb(150, 170, 210),
                       System.Drawing.Color.FromArgb(207, 145, 144),

                       System.Drawing.Color.FromArgb(60, 109, 162),
                       System.Drawing.Color.FromArgb(163, 61, 58),
                       System.Drawing.Color.FromArgb(131, 159, 68),
                       System.Drawing.Color.FromArgb(105, 80, 133),
                       System.Drawing.Color.FromArgb(56, 144, 170),
                       System.Drawing.Color.FromArgb(213, 123, 51),
                       System.Drawing.Color.FromArgb(140, 160, 200),
                       System.Drawing.Color.FromArgb(200, 135, 134), //#16

                       System.Drawing.Color.FromArgb(200, 70, 119, 172),
                       System.Drawing.Color.FromArgb(200, 173, 71, 68),
                       System.Drawing.Color.FromArgb(200, 141, 169, 78),
                       System.Drawing.Color.FromArgb(200, 115, 90, 143),
                       System.Drawing.Color.FromArgb(200, 66, 154, 180),
                       System.Drawing.Color.FromArgb(200, 223, 133, 61),
                       System.Drawing.Color.FromArgb(200, 150, 170, 210),
                       System.Drawing.Color.FromArgb(200, 207, 145, 144),
                                                     
                       System.Drawing.Color.FromArgb(200, 60, 109, 162),
                       System.Drawing.Color.FromArgb(200, 163, 61, 58),
                       System.Drawing.Color.FromArgb(200, 131, 159, 68),
                       System.Drawing.Color.FromArgb(200, 105, 80, 133),
                       System.Drawing.Color.FromArgb(200, 56, 144, 170),
                       System.Drawing.Color.FromArgb(200, 213, 123, 51),
                       System.Drawing.Color.FromArgb(200, 140, 160, 200),
                       System.Drawing.Color.FromArgb(200, 200, 135, 134) //#32
                       
                };
                #endregion

                #region Grafico 1: Sales $
                //Grafico 1: Sales $
                RadChart chart = ReportsHelper.GetPieChart("Sales " + currencySymbol);
                chart.Legend.Visible = false;


                ChartSeries s1 = new ChartSeries(string.Empty);
                s1.Type = ChartSeriesType.Pie;
                s1.Appearance.DiameterScale = 0.95f;

                ChartSeriesItem serieItem;

                int colorCount = 0;
                foreach (var item in items80Percent)
                {
                    serieItem = ReportsHelper.GetPieSeriesItem(item.Category, barColors[colorCount]);
                    serieItem.YValue = (double)item.SalesShare * 100;
                    serieItem.Label.TextBlock.Text = item.SalesShare.ToString("P0");
                    s1.AddItem(serieItem);

                    colorCount++;
                }


                chart.Series.Add(s1);

                Image salesContributionChartImage = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);

                graphicsCell = new PdfPCell(salesContributionChartImage, false);
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                graphicsCell.Padding = 0;
                graphicsTable.AddCell(graphicsCell);


                #endregion

                #region Grafico 2: Going-in Margin $

                //Going-in Margin $
                chart.ChartTitle.TextBlock.Text = "Going-in Margin " + currencySymbol;
                chart.Series.RemoveSeries();

                s1 = new ChartSeries(string.Empty);
                s1.Type = ChartSeriesType.Pie;
                s1.Appearance.DiameterScale = 0.95f;

                colorCount = 0;
                foreach (var item in items80Percent)
                {
                    serieItem = ReportsHelper.GetPieSeriesItem(item.Category, barColors[colorCount]);
                    serieItem.YValue = (double)item.GMShare * 100;
                    serieItem.Label.TextBlock.Text = item.GMShare.ToString("P0");
                    s1.AddItem(serieItem);

                    colorCount++;
                }

                chart.Series.Add(s1);



                salesContributionChartImage = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);

                graphicsCell = new PdfPCell(salesContributionChartImage, false);
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                graphicsCell.Padding = 0;
                graphicsTable.AddCell(graphicsCell);
                #endregion

                #region Grafico 3: Sales Units
                //Sales Units
                chart.ChartTitle.TextBlock.Text = "Sales Units";
                chart.Series.RemoveSeries();

                s1 = new ChartSeries(string.Empty);
                s1.Type = ChartSeriesType.Pie;
                s1.Appearance.DiameterScale = 0.95f;
                s1.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;

                colorCount = 0;
                foreach (var item in items80Percent)
                {
                    serieItem = ReportsHelper.GetPieSeriesItem(item.Category, barColors[colorCount]);
                    serieItem.YValue = (double)item.UnitsShare * 100;
                    serieItem.Label.TextBlock.Text = item.UnitsShare.ToString("P0");
                    s1.AddItem(serieItem);

                    colorCount++;
                }

                chart.Series.Add(s1);


                salesContributionChartImage = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);

                graphicsCell = new PdfPCell(salesContributionChartImage, false);
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                graphicsCell.Padding = 0;
                graphicsTable.AddCell(graphicsCell);
                #endregion

                #region Leyenda Unificada
                //Construyo la leyenda
                chart.Width = 500;
                chart.Height = 60;
                chart.PlotArea.Visible = false;
                chart.ChartTitle.Visible = false;
                chart.Legend.Visible = true;

                salesContributionChartImage = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);

                graphicsCell = new PdfPCell(salesContributionChartImage, false);
                graphicsCell.Colspan = 3;
                graphicsCell.PaddingTop = 0;
                graphicsCell.Border = PdfPCell.NO_BORDER;
                graphicsCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                graphicsCell.HorizontalAlignment = Element.ALIGN_CENTER;
                graphicsTable.AddCell(graphicsCell);
                #endregion

                document.Add(graphicsTable);

                #region Profit/Sales Makers

                items80Percent.RemoveAll(x => x.Category == "Others");
                decimal spacePerc = totalSaleSameStoreCY.LinearSpace != 0 ? items80Percent.Sum(x => x.LinearSpace) / totalSaleSameStoreCY.LinearSpace : 0;
                decimal inventoryPerc = totalSaleSameStoreCY.InventoryCost != 0 ? items80Percent.Sum(x => x.InventoryCost) / totalSaleSameStoreCY.InventoryCost : 0;
                int bottomOne = categorySalesSameStoreCY.Where(x => x.GMShare < 0.01m && x.SalesShare < 0.01m).Count();

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                Paragraph p = new Paragraph("Profit Makers:", font13bold);
                p.IndentationLeft = 60f;
                document.Add(p);
                List makersList = new List(List.UNORDERED, 30f);
                makersList.SetListSymbol("\u2022");
                makersList.IndentationLeft = 60f;

                makersList.Add(new ListItem(string.Format("80 % of Going-in Margin is generated by {0} categories.", catCount), font12));
                makersList.Add(new ListItem(string.Format("These {0} categories represent {1} of the Inventory and {2} of the Space.", catCount, inventoryPerc.ToString("P0"), spacePerc.ToString("P0")), font12));
                makersList.Add(new ListItem(string.Format("{0} categories represent less than 1% in sales and margin each.", bottomOne), font12));

                document.Add(makersList);


                #endregion


                #endregion

                #region Sales and Going in Margin Contribution - Same Store

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sales and Going in Margin Contribution - Same Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable contributionTable = new PdfPTable(new float[] { 2f, 20f, 12f, 12f, 6f, 6f, 6f, 6f, 6f, 6f });
                contributionTable.WidthPercentage = 90;
                contributionTable.SpacingBefore = 20f;
                contributionTable.HeaderRows = 3;
                contributionTable.FooterRows = 2;
                emptyTableCell.Colspan = 10;

                contributionTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                contributionTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                contributionTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                contributionTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                contributionTable.AddCell(new Phrase("#", font10boldWhite));
                contributionTable.AddCell(new Phrase("Category", font10boldWhite));
                contributionTable.AddCell(new Phrase("Sales", font10boldWhite));
                contributionTable.AddCell(new Phrase("GIM", font10boldWhite));
                contributionTable.AddCell(new Phrase("GIM %", font10boldWhite));
                contributionTable.AddCell(new Phrase("Units", font10boldWhite));
                contributionTable.AddCell(new Phrase("Sales Share", font10boldWhite));
                contributionTable.AddCell(new Phrase("GIM Share", font10boldWhite));
                contributionTable.AddCell(new Phrase("Units Share", font10boldWhite));
                contributionTable.AddCell(new Phrase("Acumm. GIM Share", font10boldWhite));

                contributionTable.AddCell(emptyTableCell);
                contributionTable.AddCell(emptyTableCell);

                contributionTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                int rank = 1;
                decimal prevAcum = 0;
                acum = 0;
                foreach (var categoryItem in categorySalesSameStoreCY.OrderByDescending(x => x.GM))
                {
                    prevAcum = acum;
                    acum += categoryItem.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        contributionTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        contributionTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    contributionTable.AddCell(new Phrase(rank.ToString(), font10));

                    contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    contributionTable.AddCell(new Phrase(categoryItem.Category, font10));

                    contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    contributionTable.AddCell(new Phrase(categoryItem.Sales.ToString("C2"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.GM.ToString("C2"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.GMPercent.ToString("P1"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.Units.ToString("N0"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.SalesShare.ToString("P1"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.GMShare.ToString("P1"), font10));

                    contributionTable.AddCell(new Phrase(categoryItem.UnitsShare.ToString("P1"), font10));

                    contributionTable.AddCell(new Phrase(acum.ToString("P1"), font10));

                    rank++;
                }

                contributionTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                contributionTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                contributionTable.AddCell(" ");

                contributionTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                contributionTable.DefaultCell.Border = PdfPCell.BOX;

                contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                contributionTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                contributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                contributionTable.AddCell(new Phrase(totalSaleSameStoreCY.Sales.ToString("C0"), font10bold));
                contributionTable.AddCell(new Phrase(totalSaleSameStoreCY.GM.ToString("C0"), font10bold));
                contributionTable.AddCell(new Phrase(totalSaleSameStoreCY.GMPercent.ToString("P0"), font10bold));
                contributionTable.AddCell(new Phrase(totalSaleSameStoreCY.Units.ToString("N0"), font10bold));
                contributionTable.AddCell(new Phrase(1.ToString("P0"), font10bold));
                contributionTable.AddCell(new Phrase(1.ToString("P0"), font10bold));
                contributionTable.AddCell(new Phrase(1.ToString("P0"), font10bold));

                contributionTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                contributionTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                contributionTable.AddCell(" ");



                document.Add(contributionTable);

                #endregion

                #region Sales and Going in Margin Performance - Same Store

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sales and Going in Margin Performance - Same Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable performanceTable = new PdfPTable(new float[] { 2f, 20f, 12f, 12f, 6f, 12f, 12f, 6f, 4f, 4f, 6f });
                performanceTable.WidthPercentage = 95;
                performanceTable.SpacingBefore = 20f;
                performanceTable.HeaderRows = 4;
                performanceTable.FooterRows = 2;
                emptyTableCell.Colspan = 11;

                performanceTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                performanceTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                performanceTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                performanceTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                performanceTable.DefaultCell.Rowspan = 2;
                performanceTable.AddCell(new Phrase("#", font10boldWhite));
                performanceTable.AddCell(new Phrase("Category", font10boldWhite));

                performanceTable.DefaultCell.Rowspan = 1;
                performanceTable.DefaultCell.Colspan = 3;
                performanceTable.AddCell(new Phrase("Sales", font10boldWhite));
                performanceTable.AddCell(new Phrase("Going-in Margin", font10boldWhite));
                performanceTable.AddCell(new Phrase("Sales Units", font10boldWhite));

                performanceTable.DefaultCell.Colspan = 1;
                performanceTable.AddCell(new Phrase("CY", font10boldWhite));
                performanceTable.AddCell(new Phrase("PY", font10boldWhite));
                performanceTable.AddCell(new Phrase("Growth", font10boldWhite));
                performanceTable.AddCell(new Phrase("CY", font10boldWhite));
                performanceTable.AddCell(new Phrase("PY", font10boldWhite));
                performanceTable.AddCell(new Phrase("Growth", font10boldWhite));
                performanceTable.AddCell(new Phrase("CY", font10boldWhite));
                performanceTable.AddCell(new Phrase("PY", font10boldWhite));
                performanceTable.AddCell(new Phrase("Growth", font10boldWhite));

                performanceTable.AddCell(emptyTableCell);
                performanceTable.AddCell(emptyTableCell);

                performanceTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;


                List<CYvsPY> growthCYvsPY = new List<CYvsPY>();
                int cyRank = 1;
                decimal cyAcumGM = 0;
                decimal cyPrevAcumGM = 0;
                foreach (var item in categorySalesSameStoreCY.OrderByDescending(x => x.GM))
                {
                    var cy = item;
                    var py = categorySalesSameStorePY.SingleOrDefault(x => x.Category == item.Category);

                    if (py == null)
                        py = new SalesCategoryComparison();

                    cyPrevAcumGM = cyAcumGM;
                    cyAcumGM += cy.GMShare;

                    growthCYvsPY.Add(new CYvsPY
                    {
                        CYRank = cyRank,
                        CY = cy,
                        PY = py,
                        SalesGrowth = py.Sales != 0 ? cy.Sales / py.Sales - 1 : 0,
                        GMGrowth = py.GM != 0 ? cy.GM / py.GM - 1 : 0,
                        UnitsGrowth = py.Units != 0 ? cy.Units / py.Units - 1 : 0,
                        InventoryGrowth = py.InventoryCost != 0 ? cy.InventoryCost / py.InventoryCost - 1 : 0,
                        CYAcumGM = cyAcumGM,
                        CYPrevAcumGM = cyPrevAcumGM
                    });

                    cyRank++;
                }

                prevAcum = 0;
                acum = 0;
                decimal growth = 0;
                foreach (var item in growthCYvsPY)
                {
                    var categoryItemCY = item.CY;
                    var categoryItemPY = item.PY;

                    prevAcum = acum;
                    acum += categoryItemCY.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        performanceTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        performanceTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    performanceTable.AddCell(new Phrase(item.CYRank.ToString(), font10));
                    performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    performanceTable.AddCell(new Phrase(categoryItemCY.Category, font10));

                    performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    performanceTable.AddCell(new Phrase(categoryItemCY.Sales.ToString("C2"), font10));
                    performanceTable.AddCell(new Phrase(categoryItemPY.Sales.ToString("C2"), font10));
                    performanceTable.AddCell(new Phrase(item.SalesGrowth.ToString("P1"), font10));

                    performanceTable.AddCell(new Phrase(categoryItemCY.GM.ToString("C2"), font10));
                    performanceTable.AddCell(new Phrase(categoryItemPY.GM.ToString("C2"), font10));
                    performanceTable.AddCell(new Phrase(item.GMGrowth.ToString("P1"), font10));

                    performanceTable.AddCell(new Phrase(categoryItemCY.Units.ToString("N0"), font10));
                    performanceTable.AddCell(new Phrase(categoryItemPY.Units.ToString("N0"), font10));
                    performanceTable.AddCell(new Phrase(item.UnitsGrowth.ToString("P1"), font10));

                    rank++;
                }

                performanceTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                performanceTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                performanceTable.AddCell(" ");

                performanceTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                performanceTable.DefaultCell.Border = PdfPCell.BOX;
                performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                performanceTable.AddCell(new Phrase("TOTAL STORE", font10bold));

                performanceTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                performanceTable.AddCell(new Phrase(totalSaleSameStoreCY.Sales.ToString("C0"), font10bold));
                performanceTable.AddCell(new Phrase(totalSaleSameStorePY.Sales.ToString("C0"), font10bold));
                growth = totalSaleSameStorePY.Sales != 0 ? totalSaleSameStoreCY.Sales / totalSaleSameStorePY.Sales - 1 : 0;
                performanceTable.AddCell(new Phrase(growth.ToString("P1"), font10bold));

                performanceTable.AddCell(new Phrase(totalSaleSameStoreCY.GM.ToString("C0"), font10bold));
                performanceTable.AddCell(new Phrase(totalSaleSameStorePY.GM.ToString("C0"), font10bold));
                growth = totalSaleSameStorePY.GM != 0 ? totalSaleSameStoreCY.GM / totalSaleSameStorePY.GM - 1 : 0;
                performanceTable.AddCell(new Phrase(growth.ToString("P1"), font10bold));

                performanceTable.AddCell(new Phrase(totalSaleSameStoreCY.Units.ToString("N0"), font10bold));
                performanceTable.AddCell(new Phrase(totalSaleSameStorePY.Units.ToString("N0"), font10bold));
                growth = totalSaleSameStorePY.Units != 0 ? totalSaleSameStoreCY.Units / totalSaleSameStorePY.Units - 1 : 0;
                performanceTable.AddCell(new Phrase(growth.ToString("P1"), font10bold));

                document.Add(performanceTable);

                #endregion

                #region Category Performance - Top & Low Performers
                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Category Performance - Top & Low Performers";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                layoutTable = new PdfPTable(1);
                layoutTable.WidthPercentage = 60;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;

                #region Categories that grew in all aspects

                var allGrewItems = growthCYvsPY.Where(x => x.SalesGrowth > 0 && x.GMGrowth > 0 && x.UnitsGrowth > 0);
                decimal salesPerc = totalSaleSameStoreCY.Sales != 0 ? allGrewItems.Sum(x => x.CY.Sales) / totalSaleSameStoreCY.Sales : 0;
                decimal gmPerc = totalSaleSameStoreCY.GM != 0 ? allGrewItems.Sum(x => x.CY.GM) / totalSaleSameStoreCY.GM : 0;
                decimal unitsPerc = totalSaleSameStoreCY.Units != 0 ? allGrewItems.Sum(x => x.CY.Units) / totalSaleSameStoreCY.Units : 0;


                List allGrewList = new List(List.UNORDERED, 30f);
                allGrewList.SetListSymbol("\u2022");
                allGrewList.IndentationLeft = 60f;

                allGrewList.Add("Categories that grew in sales, margin and units");
                List allGrewSublist = new List(List.UNORDERED, 30f);
                allGrewSublist.Add(string.Format("Represent {0} of sales, {1} of margin and {2} of units.", salesPerc.ToString("P1"), gmPerc.ToString("P1"), unitsPerc.ToString("P1")));
                allGrewList.Add(allGrewSublist);

                //document.Add(allGrewList);

                PdfPTable allGrewTable = new PdfPTable(new float[] { 3f, 20f, 10f, 10f, 10f });
                allGrewTable.SpacingBefore = 20f;
                allGrewTable.HeaderRows = 4;
                allGrewTable.FooterRows = 2;
                emptyTableCell.Colspan = 5;

                allGrewTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                allGrewTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                allGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                allGrewTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                allGrewTable.DefaultCell.Rowspan = 2;
                allGrewTable.AddCell(new Phrase("#", font10boldWhite));
                allGrewTable.AddCell(new Phrase("Category", font10boldWhite));

                allGrewTable.DefaultCell.Rowspan = 1;
                allGrewTable.DefaultCell.Colspan = 3;
                allGrewTable.AddCell(new Phrase("Growth", font10boldWhite));

                allGrewTable.DefaultCell.Colspan = 1;
                allGrewTable.AddCell(new Phrase("Sales", font10boldWhite));
                allGrewTable.AddCell(new Phrase("GIM", font10boldWhite));
                allGrewTable.AddCell(new Phrase("Units", font10boldWhite));

                allGrewTable.AddCell(emptyTableCell);
                allGrewTable.AddCell(emptyTableCell);

                foreach (var item in allGrewItems.OrderByDescending(x => x.CY.GM))
                {
                    if (item.CYPrevAcumGM <= 0.8m)
                    {
                        allGrewTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                    }
                    else if (item.CYPrevAcumGM > 0.8m && item.CYPrevAcumGM < 0.95m)
                    {
                        allGrewTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (item.CYPrevAcumGM >= 0.95m)
                    {
                        allGrewTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    allGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    allGrewTable.AddCell(new Phrase(item.CYRank.ToString(), font10));
                    allGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    allGrewTable.AddCell(new Phrase(item.CY.Category, font10));
                    allGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    allGrewTable.AddCell(new Phrase(item.SalesGrowth.ToString("P1"), font10));
                    allGrewTable.AddCell(new Phrase(item.GMGrowth.ToString("P1"), font10));
                    allGrewTable.AddCell(new Phrase(item.UnitsGrowth.ToString("P1"), font10));
                }

                //document.Add(allGrewTable);

                PdfPCell allGrewCell = new PdfPCell();
                allGrewCell.Border = PdfPCell.NO_BORDER;
                allGrewCell.AddElement(allGrewList);
                allGrewCell.AddElement(allGrewTable);

                layoutTable.AddCell(allGrewCell);
                #endregion

                #region Categories that grew in Sales and Margin

                var salesAndMarginGrewItems = growthCYvsPY.Where(x => x.SalesGrowth > 0 && x.GMGrowth > 0 && x.UnitsGrowth < 0);
                salesPerc = totalSaleSameStoreCY.Sales != 0 ? salesAndMarginGrewItems.Sum(x => x.CY.Sales) / totalSaleSameStoreCY.Sales : 0;
                gmPerc = totalSaleSameStoreCY.GM != 0 ? salesAndMarginGrewItems.Sum(x => x.CY.GM) / totalSaleSameStoreCY.GM : 0;
                unitsPerc = totalSaleSameStoreCY.Units != 0 ? salesAndMarginGrewItems.Sum(x => x.CY.Units) / totalSaleSameStoreCY.Units : 0;

                List salesAndMarginGrewList = new List(List.UNORDERED, 30f);
                salesAndMarginGrewList.SetListSymbol("\u2022");
                salesAndMarginGrewList.IndentationLeft = 60f;

                salesAndMarginGrewList.Add("Categories that grew in sales and margin despite decreasing in units");
                List salesAndMarginGrewSublist = new List(List.UNORDERED, 30f);
                salesAndMarginGrewSublist.Add(string.Format("Represent {0} of sales, {1} of margin and {2} of units.", salesPerc.ToString("P1"), gmPerc.ToString("P1"), unitsPerc.ToString("P1")));
                salesAndMarginGrewList.Add(salesAndMarginGrewSublist);

                //document.Add(salesAndMarginGrewList);


                PdfPTable salesAndMarginGrewTable = new PdfPTable(new float[] { 3f, 20f, 10f, 10f, 10f });
                salesAndMarginGrewTable.SpacingBefore = 20f;
                salesAndMarginGrewTable.HeaderRows = 4;
                salesAndMarginGrewTable.FooterRows = 2;
                emptyTableCell.Colspan = 5;

                salesAndMarginGrewTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                salesAndMarginGrewTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                salesAndMarginGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                salesAndMarginGrewTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                salesAndMarginGrewTable.DefaultCell.Rowspan = 2;
                salesAndMarginGrewTable.AddCell(new Phrase("#", font10boldWhite));
                salesAndMarginGrewTable.AddCell(new Phrase("Category", font10boldWhite));

                salesAndMarginGrewTable.DefaultCell.Rowspan = 1;
                salesAndMarginGrewTable.DefaultCell.Colspan = 3;
                salesAndMarginGrewTable.AddCell(new Phrase("Growth", font10boldWhite));

                salesAndMarginGrewTable.DefaultCell.Colspan = 1;
                salesAndMarginGrewTable.AddCell(new Phrase("Sales", font10boldWhite));
                salesAndMarginGrewTable.AddCell(new Phrase("GIM", font10boldWhite));
                salesAndMarginGrewTable.AddCell(new Phrase("Units", font10boldWhite));

                salesAndMarginGrewTable.AddCell(emptyTableCell);
                salesAndMarginGrewTable.AddCell(emptyTableCell);

                foreach (var item in salesAndMarginGrewItems.OrderByDescending(x => x.CY.GM))
                {
                    if (item.CYPrevAcumGM <= 0.8m)
                    {
                        salesAndMarginGrewTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                    }
                    else if (item.CYPrevAcumGM > 0.8m && item.CYPrevAcumGM < 0.95m)
                    {
                        salesAndMarginGrewTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (item.CYPrevAcumGM >= 0.95m)
                    {
                        salesAndMarginGrewTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    salesAndMarginGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    salesAndMarginGrewTable.AddCell(new Phrase(item.CYRank.ToString(), font10));
                    salesAndMarginGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    salesAndMarginGrewTable.AddCell(new Phrase(item.CY.Category, font10));
                    salesAndMarginGrewTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    salesAndMarginGrewTable.AddCell(new Phrase(item.SalesGrowth.ToString("P1"), font10));
                    salesAndMarginGrewTable.AddCell(new Phrase(item.GMGrowth.ToString("P1"), font10));
                    salesAndMarginGrewTable.AddCell(new Phrase(item.UnitsGrowth.ToString("P1"), font10));
                }

                //document.Add(salesAndMarginGrewTable);


                PdfPCell someGrewCell = new PdfPCell();
                someGrewCell.Border = PdfPCell.NO_BORDER;
                someGrewCell.AddElement(salesAndMarginGrewList);
                someGrewCell.AddElement(salesAndMarginGrewTable);

                layoutTable.AddCell(someGrewCell);
                #endregion

                #region Categories that decreased in all aspects

                var allDecreasedItems = growthCYvsPY.Where(x => x.SalesGrowth < 0 && x.GMGrowth < 0 && x.UnitsGrowth < 0);
                salesPerc = totalSaleSameStoreCY.Sales != 0 ? allDecreasedItems.Sum(x => x.CY.Sales) / totalSaleSameStoreCY.Sales : 0;
                gmPerc = totalSaleSameStoreCY.GM != 0 ? allDecreasedItems.Sum(x => x.CY.GM) / totalSaleSameStoreCY.GM : 0;
                unitsPerc = totalSaleSameStoreCY.Units != 0 ? allDecreasedItems.Sum(x => x.CY.Units) / totalSaleSameStoreCY.Units : 0;

                List allDecreasedList = new List(List.UNORDERED, 30f);
                allDecreasedList.SetListSymbol("\u2022");
                allDecreasedList.IndentationLeft = 60f;

                allDecreasedList.Add("Categories that decrease in sales, margin and units");
                List allDecreasedSublist = new List(List.UNORDERED, 30f);
                allDecreasedSublist.Add(string.Format("Represent {0} of sales, {1} of margin and {2} of units.", salesPerc.ToString("P1"), gmPerc.ToString("P1"), unitsPerc.ToString("P1")));
                allDecreasedList.Add(allDecreasedSublist);

                //document.Add(allDecreasedList);


                PdfPTable allDecreasedTable = new PdfPTable(new float[] { 3f, 20f, 10f, 10f, 10f });
                allDecreasedTable.SpacingBefore = 20f;
                allDecreasedTable.HeaderRows = 4;
                allDecreasedTable.FooterRows = 2;
                emptyTableCell.Colspan = 5;

                allDecreasedTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                allDecreasedTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                allDecreasedTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                allDecreasedTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                allDecreasedTable.DefaultCell.Rowspan = 2;
                allDecreasedTable.AddCell(new Phrase("#", font10boldWhite));
                allDecreasedTable.AddCell(new Phrase("Category", font10boldWhite));

                allDecreasedTable.DefaultCell.Rowspan = 1;
                allDecreasedTable.DefaultCell.Colspan = 3;
                allDecreasedTable.AddCell(new Phrase("Growth", font10boldWhite));

                allDecreasedTable.DefaultCell.Colspan = 1;
                allDecreasedTable.AddCell(new Phrase("Sales", font10boldWhite));
                allDecreasedTable.AddCell(new Phrase("GIM", font10boldWhite));
                allDecreasedTable.AddCell(new Phrase("Units", font10boldWhite));

                allDecreasedTable.AddCell(emptyTableCell);
                allDecreasedTable.AddCell(emptyTableCell);

                foreach (var item in allDecreasedItems.OrderByDescending(x => x.CY.GM))
                {
                    if (item.CYPrevAcumGM <= 0.8m)
                    {
                        allDecreasedTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                    }
                    else if (item.CYPrevAcumGM > 0.8m && item.CYPrevAcumGM < 0.95m)
                    {
                        allDecreasedTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (item.CYPrevAcumGM >= 0.95m)
                    {
                        allDecreasedTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    allDecreasedTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    allDecreasedTable.AddCell(new Phrase(item.CYRank.ToString(), font10));
                    allDecreasedTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    allDecreasedTable.AddCell(new Phrase(item.CY.Category, font10));
                    allDecreasedTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    allDecreasedTable.AddCell(new Phrase(item.SalesGrowth.ToString("P1"), font10));
                    allDecreasedTable.AddCell(new Phrase(item.GMGrowth.ToString("P1"), font10));
                    allDecreasedTable.AddCell(new Phrase(item.UnitsGrowth.ToString("P1"), font10));
                }

                //document.Add(allDecreasedTable);
                PdfPCell allDecreasedCell = new PdfPCell();
                allDecreasedCell.Border = PdfPCell.NO_BORDER;
                allDecreasedCell.AddElement(allDecreasedList);
                allDecreasedCell.AddElement(allDecreasedTable);

                layoutTable.AddCell(allDecreasedCell);
                #endregion

                document.Add(layoutTable);
                #endregion

                #region Impact of Study Recommendations

                var spaceRows = ReportsRepository.GetSalesCategoryComparisonBySpace(rangeReview.Id, 0, true, 1);
                var salesBySpace = spaceRows.ConvertAll<SalesCategoryComparisonBySpace>(row => new SalesCategoryComparisonBySpace(row));

                if (totalSalesAverageStoreDelistCY != null)
                {
                    #region Shares: Skus ToDelist vs Skus to Keep

                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Impact of Study Recommendations";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    document.Add(new Paragraph(" "));

                    decimal delistSKUsPerc = totalSaleAverageStoreCY.SKUs != 0 ? totalSalesAverageStoreDelistCY.SKUs / (decimal)totalSaleAverageStoreCY.SKUs : 0;
                    decimal delistSKUsSalesPerc = totalSaleAverageStoreCY.Sales != 0 ? totalSalesAverageStoreDelistCY.Sales / totalSaleAverageStoreCY.Sales : 0;

                    List bulletList = new List(List.UNORDERED, 30f);
                    bulletList.SetListSymbol("\u2022");
                    bulletList.IndentationLeft = 60f;
                    bulletList.Add(new ListItem(string.Format("De-listing of {0} SKUs ({1}), wich represent {2} of sales.", totalSalesAverageStoreDelistCY.SKUs, delistSKUsPerc.ToString("P1"), delistSKUsSalesPerc.ToString("P1")), font14));
                    document.Add(bulletList);

                    PdfPTable delistTable = new PdfPTable(7);
                    delistTable.SpacingBefore = 25f;
                    delistTable.SpacingAfter = 25f;
                    delistTable.WidthPercentage = 65;
                    delistTable.DefaultCell.BorderColorTop = new BaseColor(124, 149, 180);
                    delistTable.DefaultCell.BorderColorBottom = new BaseColor(124, 149, 180);
                    delistTable.DefaultCell.BorderWidthTop = 1.5f;
                    delistTable.DefaultCell.BorderWidthBottom = 0.2f;
                    delistTable.DefaultCell.BorderWidthLeft = 0;
                    delistTable.DefaultCell.BorderWidthRight = 0;
                    delistTable.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);

                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    delistTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    delistTable.AddCell(new Phrase("Proposal", font11bold));
                    delistTable.AddCell(new Phrase("SKUs", font11bold));
                    delistTable.AddCell(new Phrase("Sales " + currencySymbol, font11bold));
                    delistTable.AddCell(new Phrase("GIM " + currencySymbol, font11bold));
                    delistTable.AddCell(new Phrase("Units", font11bold));
                    delistTable.AddCell(new Phrase("Inventory " + currencySymbol, font11bold));
                    delistTable.AddCell(new Phrase("Space", font11bold));

                    delistTable.DefaultCell.BorderWidthTop = 0.2f;
                    delistTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    delistTable.AddCell(new Phrase("SKUs to Keep", font11));
                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.SKUs - totalSalesAverageStoreDelistCY.SKUs).ToString("N0"), font11));
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.Sales - totalSalesAverageStoreDelistCY.Sales).ToString("C0"), font11));
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.GM - totalSalesAverageStoreDelistCY.GM).ToString("C0"), font11));
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.Units - totalSalesAverageStoreDelistCY.Units).ToString("N0"), font11));
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.InventoryCost - totalSalesAverageStoreDelistCY.InventoryCost).ToString("C0"), font11));
                    delistTable.AddCell(new Phrase((totalSaleAverageStoreCY.LinearSpace - totalSalesAverageStoreDelistCY.LinearSpace).ToString("N0") + " mt.", font11));

                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    delistTable.AddCell(new Phrase("SKUs to De-list", font11));
                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.SKUs.ToString("N0"), font11));
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.Sales.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.GM.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.Units.ToString("N0"), font11));
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.InventoryCost.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.LinearSpace.ToString("N0") + " mt.", font11));

                    delistTable.DefaultCell.BorderWidthBottom = 1.5f;

                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    delistTable.AddCell(new Phrase("Total", font11));
                    delistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.SKUs.ToString("N0"), font11));
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.Sales.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.GM.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.Units.ToString("N0"), font11));
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.InventoryCost.ToString("C0"), font11));
                    delistTable.AddCell(new Phrase(totalSaleAverageStoreCY.LinearSpace.ToString("N0") + " mt.", font11));

                    document.Add(delistTable);

                    decimal delistSalesPerc = totalSaleAverageStoreCY.Sales != 0 ? totalSalesAverageStoreDelistCY.Sales / totalSaleAverageStoreCY.Sales : 0;
                    decimal delistGMPerc = totalSaleAverageStoreCY.GM != 0 ? totalSalesAverageStoreDelistCY.GM / totalSaleAverageStoreCY.GM : 0;
                    decimal delistUnitsPerc = totalSaleAverageStoreCY.Units != 0 ? totalSalesAverageStoreDelistCY.Units / totalSaleAverageStoreCY.Units : 0;
                    decimal delistInventoryPerc = totalSaleAverageStoreCY.InventoryCost != 0 ? totalSalesAverageStoreDelistCY.InventoryCost / totalSaleAverageStoreCY.InventoryCost : 0;
                    decimal delistSpacePerc = totalSaleAverageStoreCY.LinearSpace != 0 ? totalSalesAverageStoreDelistCY.LinearSpace / totalSaleAverageStoreCY.LinearSpace : 0;


                    RadChart delistChart = ReportsHelper.GetBarsChart(null);

                    ChartSeries toKeepSerie = new ChartSeries("SKUs to Keep");
                    toKeepSerie.Type = ChartSeriesType.StackedBar100;
                    toKeepSerie.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                    toKeepSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 0f));
                    toKeepSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0 + 16], 0.5f));
                    toKeepSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 1f));
                    toKeepSerie.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                    toKeepSerie.Appearance.Border.Visible = false;


                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.SKUs - totalSalesAverageStoreDelistCY.SKUs), (1 - delistSKUsPerc).ToString("P0"));
                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.Sales - totalSalesAverageStoreDelistCY.Sales), (1 - delistSalesPerc).ToString("P0"));
                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.GM - totalSalesAverageStoreDelistCY.GM), (1 - delistGMPerc).ToString("P0"));
                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.Units - totalSalesAverageStoreDelistCY.Units), (1 - delistUnitsPerc).ToString("P0"));
                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.InventoryCost - totalSalesAverageStoreDelistCY.InventoryCost), (1 - delistInventoryPerc).ToString("P0"));
                    toKeepSerie.AddItem((double)(totalSaleAverageStoreCY.LinearSpace - totalSalesAverageStoreDelistCY.LinearSpace), (1 - delistSpacePerc).ToString("P0"));

                    foreach (ChartSeriesItem sit in toKeepSerie.Items)
                    {
                        sit.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        sit.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        sit.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                    }

                    ChartSeries toDelistSerie = new ChartSeries("SKUs to De-list");
                    toDelistSerie.Type = ChartSeriesType.StackedBar100;
                    toDelistSerie.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                    toDelistSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1], 0f));
                    toDelistSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1 + 16], 0.5f));
                    toDelistSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1], 1f));
                    toDelistSerie.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                    toDelistSerie.Appearance.Border.Visible = false;

                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.SKUs, delistSKUsPerc.ToString("P0"));
                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.Sales, delistSalesPerc.ToString("P0"));
                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.GM, delistGMPerc.ToString("P0"));
                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.Units, delistUnitsPerc.ToString("P0"));
                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.InventoryCost, delistInventoryPerc.ToString("P0"));
                    toDelistSerie.AddItem((double)totalSalesAverageStoreDelistCY.LinearSpace, delistSpacePerc.ToString("P0"));

                    foreach (ChartSeriesItem sit in toDelistSerie.Items)
                    {
                        sit.Label.Appearance.LabelLocation = Telerik.Charting.Styles.StyleSeriesItemLabel.ItemLabelLocation.Inside;
                        sit.Label.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Center;
                        sit.Label.TextBlock.Appearance.TextProperties.Color = System.Drawing.Color.White;
                    }

                    delistChart.AddChartSeries(toKeepSerie);
                    delistChart.AddChartSeries(toDelistSerie);

                    delistChart.PlotArea.XAxis.AddItem("SKUs");
                    delistChart.PlotArea.XAxis.AddItem("Sales " + currencySymbol);
                    delistChart.PlotArea.XAxis.AddItem("GIM " + currencySymbol);
                    delistChart.PlotArea.XAxis.AddItem("Units");
                    delistChart.PlotArea.XAxis.AddItem("Inventory " + currencySymbol);
                    delistChart.PlotArea.XAxis.AddItem("Space");

                    Image delistChartImage = Image.GetInstance(delistChart.GetBitmap(), BaseColor.WHITE);
                    delistChartImage.Alignment = Image.ALIGN_CENTER;
                    document.Add(delistChartImage);

                    #endregion
                    
                    #region De-listing Impact on Space

                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Impact of Study Recommendations";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    bulletList = new List(List.UNORDERED, 30f);
                    bulletList.SetListSymbol("\u2022");
                    bulletList.IndentationLeft = 20f;
                    bulletList.Add(new ListItem("De-listing proposal impact on Space", font14));
                    document.Add(bulletList);

                    Image chart1Image = null;
                    Image chart2Image = null;
                    Image chart3Image = null;

                    decimal totalSpace = salesBySpace.Where(x => !x.IsDeletedRangeReview).Sum(x => x.LinearSpaceMts);
                    if (totalSpace != 0)
                    {
                        //Total Space Chart
                        var chartSpaceDataQuery = from item in salesBySpace.Where(x => !x.IsDeletedRangeReview && x.LinearSpaceMts != 0)
                                                  group item by item.Location1 into g
                                                  select new { Location1 = g.Key, SpacePerc = (g.Sum(x => x.LinearSpaceMts) / totalSpace) };

                        var chartSpaceData = chartSpaceDataQuery.OrderByDescending(x => x.SpacePerc).Take(6).ToList();

                        if (chartSpaceDataQuery.Count() > 6)
                        {
                            chartSpaceData.Add(new
                            {
                                Location1 = "Other Locations",
                                SpacePerc = chartSpaceDataQuery.Where(x => !chartSpaceData.Contains(x)).Sum(x => x.SpacePerc)
                            });
                        }

                        chart = ReportsHelper.GetPieChart(string.Format("Space Total: ({0} mt.)", totalSpace.ToString("N0")));
                        chart.Width = 350;
                        chart.Height = 200;
                        //chart.ChartTitle.TextBlock.Appearance.TextProperties.Font = new System.Drawing.Font("Calibri", 9, System.Drawing.FontStyle.Bold);
                        chart.Legend.Appearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Right;
                        chart.Legend.Appearance.Overflow = Telerik.Charting.Styles.Overflow.Column;
                        //chart.Legend.Appearance.ItemTextAppearance.TextProperties.Font = new System.Drawing.Font("Calibri", 7, System.Drawing.FontStyle.Regular);

                        s1 = new ChartSeries(string.Empty);
                        s1.Type = ChartSeriesType.Pie;
                        s1.Appearance.DiameterScale = 1;
                        s1.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;

                        colorCount = 0;
                        foreach (var item in chartSpaceData.OrderByDescending(x => x.SpacePerc))
                        {
                            serieItem = ReportsHelper.GetPieSeriesItem(item.Location1, barColors[colorCount]);
                            serieItem.YValue = (double)item.SpacePerc * 100;
                            serieItem.Label.TextBlock.Text = item.SpacePerc.ToString("P0");

                            s1.AddItem(serieItem);
                            colorCount++;
                        }

                        chart.Series.Add(s1);

                        chart1Image = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);


                        if (totalSpace != 0)
                        {
                            //De-listed Space Chart
                            totalSpace = salesBySpace.Where(x => x.Delist && !x.IsDeletedRangeReview).Sum(x => x.LinearSpaceMts);

                            var chartDelistSpaceData = from item in salesBySpace.Where(x => x.LinearSpaceMts != 0 && x.Delist && !x.IsDeletedRangeReview)
                                                       group item by item.Location1 into g
                                                       select new { Location1 = g.Key, SpacePerc = (g.Sum(x => x.LinearSpaceMts) / totalSpace) };


                            chart.Width = 300;
                            chart.Legend.Visible = false;
                            chart.ChartTitle.TextBlock.Text = string.Format("Space: SKUs to De-list ({0} mt)", totalSpace.ToString("N0"));
                            chart.Series.RemoveSeries();

                            s1 = new ChartSeries(string.Empty);
                            s1.Type = ChartSeriesType.Pie;
                            s1.Appearance.DiameterScale = 1;
                            s1.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;

                            colorCount = 0;
                            foreach (var orderItem in chartSpaceData.OrderByDescending(x => x.SpacePerc))
                            {
                                var item = chartDelistSpaceData.SingleOrDefault(x => x.Location1 == orderItem.Location1);
                                if (item != null)
                                {
                                    serieItem = ReportsHelper.GetPieSeriesItem(item.Location1, barColors[colorCount]);
                                    serieItem.YValue = (double)item.SpacePerc * 100;
                                    serieItem.Label.TextBlock.Text = item.SpacePerc.ToString("P0");
                                    s1.AddItem(serieItem);
                                }
                                colorCount++;
                            }

                            chart.Series.Add(s1);

                            chart2Image = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);
                        }
                    }
                    //SKUs to De-list: POG / Listing / No Space
                    decimal totalDelistedSales = salesBySpace.Where(x => x.Delist && !x.IsDeletedRangeReview).Sum(x => x.Sales);

                    if (totalDelistedSKUs != 0 && totalDelistedSales != 0)
                    {
                        var planogramChartData = from item in salesBySpace.Where(x => x.Delist && !x.IsDeletedRangeReview)
                                                 group item by item.PlanogramTypeName into g
                                                 select new { PlanogramTypeName = g.Key, SalesPerc = g.Sum(x => x.Sales) / totalDelistedSales, SKUsPerc = g.Count() / totalDelistedSKUs };

                        chart = ReportsHelper.GetBarsChart("SKUs to De-list: POG / Listing / No Space");

                        s1 = new ChartSeries("% Sales");
                        s1.Type = ChartSeriesType.Bar;
                        //s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                        //s1.Appearance.FillStyle.MainColor = barColors[0];
                        s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 0f));
                        s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0 + 16], 0.5f));
                        s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 1f));
                        s1.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                        s1.Appearance.Border.Visible = false;

                        ChartSeries s2 = new ChartSeries("% SKUs");
                        s2.Type = ChartSeriesType.Bar;
                        //s2.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                        //s2.Appearance.FillStyle.MainColor = barColors[1];
                        s2.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                        s2.Appearance.FillStyle.MainColor = barColors[1];
                        s2.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                        s2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1], 0f));
                        s2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1 + 16], 0.5f));
                        s2.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[1], 1f));
                        s2.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                        s2.Appearance.Border.Visible = false;


                        foreach (var item in planogramChartData.OrderByDescending(x => x.SalesPerc))
                        {
                            //Sales Serie
                            serieItem = ReportsHelper.GetBarsSeriesItem(item.PlanogramTypeName);
                            serieItem.YValue = (double)item.SalesPerc * 100;
                            serieItem.Label.TextBlock.Text = item.SalesPerc.ToString("P0");
                            s1.AddItem(serieItem);

                            //SKUs Serie
                            serieItem = ReportsHelper.GetBarsSeriesItem(item.PlanogramTypeName);
                            serieItem.YValue = (double)item.SKUsPerc * 100;
                            serieItem.Label.TextBlock.Text = item.SKUsPerc.ToString("P0");
                            s2.AddItem(serieItem);
                        }

                        chart.Series.Add(s1);
                        chart.Series.Add(s2);

                        chart.PlotArea.XAxis.Clear();
                        foreach (var item in planogramChartData.OrderByDescending(x => x.SalesPerc))
                        {
                            chart.PlotArea.XAxis.AddItem(item.PlanogramTypeName);
                        }

                        chart3Image = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);
                    }

                    layoutTable = new PdfPTable(new float[] { 55f, 45f });
                    layoutTable.WidthPercentage = 100;
                    layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                    layoutTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    layoutTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    layoutTable.DefaultCell.PaddingTop = 0f;
                    layoutTable.DefaultCell.PaddingLeft = 10f;
                    layoutTable.SpacingBefore = 10f;

                    layoutTable.AddCell(chart1Image);
                    layoutTable.AddCell(chart2Image);
                    layoutTable.AddCell(chart3Image);
                    layoutTable.AddCell(" ");

                    document.Add(layoutTable);

                    #endregion

                    #region De-listing Impact on Inventory

                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Impact of Study Recommendations";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    bulletList = new List(List.UNORDERED, 30f);
                    bulletList.SetListSymbol("\u2022");
                    bulletList.IndentationLeft = 20f;
                    bulletList.Add(new ListItem("De-listing proposal impact on Inventory", font14));
                    document.Add(bulletList);

                    RadChart delistInventoryChart = ReportsHelper.GetPieChart(string.Format("Inventory Reduction: {0}", totalSalesAverageStoreDelistCY.InventoryCost.ToString("C0")));
                    delistInventoryChart.Height = 350;
                    delistInventoryChart.Width = 350;

                    ChartSeries delistInventorySerie = new ChartSeries(string.Empty);
                    delistInventorySerie.Type = ChartSeriesType.Pie;
                    delistInventorySerie.Appearance.DiameterScale = 1;
                    delistInventorySerie.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;

                    ChartSeriesItem delistInventoryItem;
                    decimal resultPerc = 0;
                    colorCount = 0;

                    int limit = 4;
                    var items = categorySalesAverageStoreDelist.Where(x => !x.IsPriorYear).OrderByDescending(x => x.InventoryCost).Take(limit).ToList();
                    var itemsAndOther = items;
                    if (categorySalesAverageStoreDelist.Where(x => !x.IsPriorYear).Count() > 4)
                    {
                        itemsAndOther.Add(new SalesCategoryComparison
                            {
                                Category = "Others",
                                InventoryCost = categorySalesAverageStoreDelist.Where(x => !x.IsPriorYear).Where(x => !items.Contains(x)).Sum(x => x.InventoryCost)
                            });
                    }

                    foreach (var delistItem in itemsAndOther)
                    {
                        resultPerc = totalSalesAverageStoreDelistCY.InventoryCost != 0 ? delistItem.InventoryCost / totalSalesAverageStoreDelistCY.InventoryCost : 0;

                        delistInventoryItem = ReportsHelper.GetPieSeriesItem(delistItem.Category, barColors[colorCount]);
                        delistInventoryItem.YValue = (double)resultPerc * 100;
                        delistInventoryItem.Label.TextBlock.Text = resultPerc.ToString("P0");
                        delistInventorySerie.AddItem(delistInventoryItem);

                        colorCount++;
                    }

                    delistInventoryChart.Series.Add(delistInventorySerie);


                    Image delistInvChartImage = Image.GetInstance(delistInventoryChart.GetBitmap(), BaseColor.WHITE);
                    delistInvChartImage.Alignment = Image.ALIGN_LEFT;

                    document.Add(delistInvChartImage);

                    #endregion

                    #region Stock of not analyzed Skus

                    ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Impact of Study Recommendations";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    PdfPTable layout = new PdfPTable(2);
                    layout.WidthPercentage = 100;
                    layout.DefaultCell.Border = PdfPCell.NO_BORDER;


                    bulletList = new List(List.UNORDERED, 30f);
                    bulletList.SetListSymbol("\u2022");
                    bulletList.IndentationLeft = 20f;
                    bulletList.Add(new ListItem("De-listing proposal impact on inventories", font14));
                    object[] res = InventoriesRepository.GetTotalStoresAndLastUpdate(rangeReview.Id);
                    if (res != null)
                    {
                        bulletList.Add(new ListItem(string.Format("Stock 'On Hand' in {0} stores, on {1}"
                                                                    , (int)res[0]
                                                                    , ((DateTime)res[1]).AddMonths(1).AddDays(-1).ToString("MMM dd (yyyy)")), font14));
                    }

                    PdfPCell cell = new PdfPCell();
                    cell.Border = PdfPCell.NO_BORDER;
                    cell.AddElement(bulletList);
                    layout.AddCell(cell);

                    var totalRows = ReportsRepository.GetInventoryOfAnalyzedArticles(rangeReview.Id, 2);
                    var analizedArticles = totalRows.ConvertAll<ArticleInventoryAndSales>(row => new ArticleInventoryAndSales(row)).Where(x => !x.IsDeletedRangeReview).ToList();

                    var notAnalizedArticles = totalRows.ConvertAll<ArticleInventoryAndSales>(row => new ArticleInventoryAndSales(row)).Where(x => x.IsDeletedRangeReview).ToList();

                    decimal notAnalizedArticlesTotalCost = notAnalizedArticles.Sum(x => x.InventoryCost);

                    //Pie Chart
                    chart = ReportsHelper.GetPieChart(string.Format("Stock from Not Analyzed Articles: {0}", notAnalizedArticlesTotalCost.ToString("C0")));
                    chart.Width = 350;
                    chart.Height = 350;

                    s1 = new ChartSeries(string.Empty);
                    s1.Type = ChartSeriesType.Pie;
                    s1.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;
                    s1.Appearance.DiameterScale = 1;


                    if (notAnalizedArticlesTotalCost != 0)
                    {
                        var query = (from item in notAnalizedArticles
                                     group item by item.Category into g
                                     select new { Category = g.Key, InventoryCostPerc = g.Sum(x => x.InventoryCost) / notAnalizedArticlesTotalCost }).ToList();


                        var pieChartData = query.OrderByDescending(x => x.InventoryCostPerc).Take(7).ToList();
                        pieChartData.Add(new { Category = "Others", InventoryCostPerc = query.Where(x => !pieChartData.Select(y => y.Category).Contains(x.Category)).Sum(x => x.InventoryCostPerc) });

                        colorCount = 0;
                        foreach (var item in pieChartData.OrderByDescending(x => x.InventoryCostPerc))
                        {
                            serieItem = ReportsHelper.GetPieSeriesItem(item.Category, barColors[colorCount]);
                            serieItem.YValue = (double)item.InventoryCostPerc * 100;
                            serieItem.Label.TextBlock.Text = item.InventoryCostPerc.ToString("P0");
                            s1.AddItem(serieItem);

                            colorCount++;
                        }
                    }

                    chart.Series.Add(s1);
                    chart1Image = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);
                    layout.DefaultCell.Rowspan = 2;
                    layout.AddCell(chart1Image);



                    //Bars Chart
                    chart = ReportsHelper.GetBarsChart("Stock Cost (%)");
                    chart.Width = 350;
                    chart.Height = 250;
                    chart.Legend.Visible = false;

                    s1 = new ChartSeries(string.Empty);
                    s1.Type = ChartSeriesType.Bar;
                    //s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                    //s1.Appearance.FillStyle.MainColor = barColors[0];
                    s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                    s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 0f));
                    s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0 + 16], 0.5f));
                    s1.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 1f));
                    s1.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                    s1.Appearance.Border.Visible = false;


                    decimal totalStockCost = totalRows.Sum(x => x.InventoryCost);
                    decimal activeCost = analizedArticles.Where(x => !x.Delist).Sum(x => x.InventoryCost);
                    decimal delistCost = analizedArticles.Where(x => x.Delist).Sum(x => x.InventoryCost);
                    decimal notAnalyzedCost = notAnalizedArticles.Sum(x => x.InventoryCost);

                    serieItem = ReportsHelper.GetBarsSeriesItem(string.Empty);

                    if (totalStockCost != 0)
                    {
                        serieItem.YValue = (double)activeCost;
                        serieItem.Label.TextBlock.Text = (activeCost / totalStockCost).ToString("P1");
                        s1.AddItem(serieItem);

                        serieItem = ReportsHelper.GetBarsSeriesItem(string.Empty);
                        serieItem.YValue = (double)delistCost;
                        serieItem.Label.TextBlock.Text = (delistCost / totalStockCost).ToString("P1");
                        s1.AddItem(serieItem);


                        serieItem = ReportsHelper.GetBarsSeriesItem(string.Empty);
                        serieItem.YValue = (double)notAnalyzedCost;
                        serieItem.Label.TextBlock.Text = (notAnalyzedCost / totalStockCost).ToString("P1");
                        s1.AddItem(serieItem);
                    }

                    chart.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.True;

                    chart.PlotArea.XAxis.Clear();
                    chart.PlotArea.XAxis.AddItem("Active SKUs");
                    chart.PlotArea.XAxis.AddItem("De-list Proposal");
                    chart.PlotArea.XAxis.AddItem("Not Analyzed SKUs");

                    chart.Series.Add(s1);
                    chart1Image = Image.GetInstance(chart.GetBitmap(), BaseColor.WHITE);
                    layout.DefaultCell.Rowspan = 1;
                    layout.AddCell(chart1Image);

                    decimal totalArticleSales = paretoItems.Sum(x => x.Sales);
                    decimal activeSales = paretoItems.Where(x => !x.IsDeletedRangeReview && !x.Delist).Sum(x => x.Sales);
                    decimal delistSales = paretoItems.Where(x => x.Delist).Sum(x => x.Sales);
                    decimal notAnalyzedSales = paretoItems.Where(x => x.IsDeletedRangeReview).Sum(x => x.Sales);


                    //Inventory Table
                    PdfPTable articlesInventoryTable = new PdfPTable(new float[] {4f, 40f, 20f, 20f, 20f });
                    articlesInventoryTable.WidthPercentage = 40;
                    articlesInventoryTable.SpacingBefore = 20f;
                    articlesInventoryTable.DefaultCell.BackgroundColor = new BaseColor(174, 206, 220);
                    articlesInventoryTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                    articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    emptyTableCell.Colspan = 1;

                    if (totalStockCost != 0 && totalArticleSales != 0)
                    {
                        articlesInventoryTable.AddCell(emptyTableCell);
                        articlesInventoryTable.AddCell(new Phrase("Status", font10bold));
                        articlesInventoryTable.AddCell(new Phrase(string.Format("Inventory ({0})", currencySymbol), font10bold));
                        articlesInventoryTable.AddCell(new Phrase("Inventory (%)", font10bold));
                        articlesInventoryTable.AddCell(new Phrase("Sales (%)", font10bold));

                        articlesInventoryTable.AddCell(emptyTableCell);
                        articlesInventoryTable.DefaultCell.BackgroundColor = new BaseColor(215, 236, 244);
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        articlesInventoryTable.AddCell(new Phrase("Active SKUs", font10));
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        articlesInventoryTable.AddCell(new Phrase(activeCost.ToString("C0"), font10));
                        articlesInventoryTable.AddCell(new Phrase((activeCost / totalStockCost).ToString("P1"), font10));
                        articlesInventoryTable.AddCell(new Phrase((activeSales / totalArticleSales).ToString("P1"), font10));

                        articlesInventoryTable.AddCell(emptyTableCell);
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        articlesInventoryTable.AddCell(new Phrase("Tryada De-list Proposal", font10));
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        articlesInventoryTable.AddCell(new Phrase(delistCost.ToString("C0"), font10));
                        articlesInventoryTable.AddCell(new Phrase((delistCost / totalStockCost).ToString("P1"), font10));
                        articlesInventoryTable.AddCell(new Phrase((delistSales / totalArticleSales).ToString("P1"), font10));

                        articlesInventoryTable.AddCell(emptyTableCell);
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        articlesInventoryTable.AddCell(new Phrase("Not Analyzed SKUs", font10));
                        articlesInventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        articlesInventoryTable.AddCell(new Phrase(notAnalyzedCost.ToString("C0"), font10));
                        articlesInventoryTable.AddCell(new Phrase((notAnalyzedCost / totalStockCost).ToString("P1"), font10));
                        articlesInventoryTable.AddCell(new Phrase((notAnalyzedSales / totalArticleSales).ToString("P1"), font10));
                    }

                    //layout.DefaultCell.Colspan = 2;
                    layout.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    layout.AddCell(articlesInventoryTable);
                    layout.AddCell(" ");


                    document.Add(layout);

                    #endregion
                }

                #endregion
                
                #endregion
                
                #region Product Range Analysis Highlights - Inventories

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                caratula2 = new Paragraph();
                caratula2.SpacingBefore = 160f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.MultipliedLeading = 2.5f;
                caratula2.Add(new Paragraph("Product Range Analysis Highlights", font30));
                caratula2.Add(new Phrase("Inventories", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Inventories Performance - Same Store

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Inventories Performance - Same Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable inventoryTable = new PdfPTable(new float[] { 3f, 16f, 9f, 9f, 6f, 2f, 6f, 6f, 6f, 6f });
                inventoryTable.WidthPercentage = 95;
                inventoryTable.SpacingBefore = 20f;
                inventoryTable.HeaderRows = 4;
                inventoryTable.FooterRows = 2;
                emptyTableCell.Colspan = 10;

                PdfPCell blankCell = new PdfPCell();
                blankCell.Border = PdfPCell.NO_BORDER;

                inventoryTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                inventoryTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                inventoryTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                inventoryTable.DefaultCell.Rowspan = 2;
                inventoryTable.AddCell(new Phrase("#", font10boldWhite));
                inventoryTable.AddCell(new Phrase("Category", font10boldWhite));

                inventoryTable.DefaultCell.Rowspan = 1;
                inventoryTable.DefaultCell.Colspan = 3;
                inventoryTable.AddCell(new Phrase("Inventory", font10boldWhite));

                inventoryTable.AddCell(blankCell);

                inventoryTable.DefaultCell.Colspan = 2;
                inventoryTable.AddCell(new Phrase("Current Year", font10boldWhite));
                inventoryTable.AddCell(new Phrase("Prior Year", font10boldWhite));

                inventoryTable.DefaultCell.Colspan = 1;
                inventoryTable.AddCell(new Phrase("Current Year", font10boldWhite));
                inventoryTable.AddCell(new Phrase("Prior Year", font10boldWhite));
                inventoryTable.AddCell(new Phrase("Growth", font10boldWhite));

                inventoryTable.AddCell(blankCell);

                inventoryTable.AddCell(new Phrase("Inventory Days", font10boldWhite));
                inventoryTable.AddCell(new Phrase("GMROI (Monthly)", font10boldWhite));

                inventoryTable.AddCell(new Phrase("Inventory Days", font10boldWhite));
                inventoryTable.AddCell(new Phrase("GMROI (Monthly)", font10boldWhite));

                inventoryTable.AddCell(emptyTableCell);
                inventoryTable.AddCell(emptyTableCell);

                foreach (var item in growthCYvsPY.OrderByDescending(x => x.CY.GM))
                {
                    if (item.CYPrevAcumGM <= 0.8m)
                    {
                        inventoryTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                    }
                    else if (item.CYPrevAcumGM > 0.8m && item.CYPrevAcumGM < 0.95m)
                    {
                        inventoryTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (item.CYPrevAcumGM >= 0.95m)
                    {
                        inventoryTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    inventoryTable.AddCell(new Phrase(item.CYRank.ToString(), font10));
                    inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    inventoryTable.AddCell(new Phrase(item.CY.Category, font10));

                    inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    inventoryTable.AddCell(new Phrase(item.CY.InventoryCost.ToString("C2"), font10));
                    inventoryTable.AddCell(new Phrase(item.PY.InventoryCost.ToString("C2"), font10));
                    inventoryTable.AddCell(new Phrase(item.InventoryGrowth.ToString("P1"), font10));

                    inventoryTable.AddCell(blankCell);

                    inventoryTable.AddCell(new Phrase(item.CY.InvDays.ToString("N0"), font10));
                    inventoryTable.AddCell(new Phrase(item.CY.GMROI.ToString("N2"), item.CY.GMROI < totalSaleSameStoreCY.GMROI ? font10boldRed : font10));

                    inventoryTable.AddCell(new Phrase(item.PY.InvDays.ToString("N0"), font10));
                    inventoryTable.AddCell(new Phrase(item.PY.GMROI.ToString("N2"), item.PY.GMROI < totalSaleSameStorePY.GMROI ? font10boldRed : font10));
                }

                inventoryTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                inventoryTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                inventoryTable.AddCell(" ");

                inventoryTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                inventoryTable.DefaultCell.Border = PdfPCell.BOX;
                inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                inventoryTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                inventoryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                inventoryTable.AddCell(new Phrase(totalSaleSameStoreCY.InventoryCost.ToString("C0"), font10bold));
                inventoryTable.AddCell(new Phrase(totalSaleSameStorePY.InventoryCost.ToString("C0"), font10bold));
                growth = totalSaleSameStorePY.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / totalSaleSameStorePY.InventoryCost - 1 : 0;
                inventoryTable.AddCell(new Phrase(growth.ToString("P1"), font10bold));

                inventoryTable.AddCell(blankCell);

                inventoryTable.AddCell(new Phrase(totalSaleSameStoreCY.InvDays.ToString("N0"), font10bold));
                inventoryTable.AddCell(new Phrase(totalSaleSameStoreCY.GMROI.ToString("N2"), font10bold));

                inventoryTable.AddCell(new Phrase(totalSaleSameStorePY.InvDays.ToString("N0"), font10bold));
                inventoryTable.AddCell(new Phrase(totalSaleSameStorePY.GMROI.ToString("N2"), font10bold));


                document.Add(inventoryTable);

                #endregion

                #region Inventories Benchmarking - Same Store

                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Inventories Benchmarking - Same Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                RadChart inventoryChart = ReportsHelper.GetBarsChart("Total Store Inventory");
                inventoryChart.Height = 250;
                inventoryChart.Width = 400;


                ChartSeries costSerie = new ChartSeries("Inventory");
                costSerie.Type = ChartSeriesType.Bar;
                //costSerie.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                //costSerie.Appearance.FillStyle.MainColor = barColors[0];
                costSerie.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.ComplexGradient;
                costSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 0f));
                costSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0 + 16], 0.5f));
                costSerie.Appearance.FillStyle.FillSettings.ComplexGradient.Add(new GradientElement(barColors[0], 1f));
                costSerie.Appearance.FillStyle.FillSettings.GradientMode = Telerik.Charting.Styles.GradientFillStyle.Horizontal;
                costSerie.Appearance.Border.Visible = false;
                costSerie.Appearance.TextAppearance.TextProperties.Font = new System.Drawing.Font("calibri", 9f, System.Drawing.FontStyle.Regular);
                costSerie.Appearance.TextAppearance.TextProperties.Color = System.Drawing.Color.Black;
                costSerie.AddItem((double)totalSaleSameStoreCY.InventoryCost / 1000, totalSaleSameStoreCY.InventoryCost.ToString("C2"));
                costSerie.AddItem((double)totalSaleSameStorePY.InventoryCost / 1000, totalSaleSameStorePY.InventoryCost.ToString("C2"));
                inventoryChart.AddChartSeries(costSerie);

                ChartSeries invDaysSerie = new ChartSeries("Inv Days");
                invDaysSerie.Type = ChartSeriesType.Line;
                invDaysSerie.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                invDaysSerie.Appearance.FillStyle.MainColor = barColors[1];
                invDaysSerie.Appearance.TextAppearance.TextProperties.Font = new System.Drawing.Font("calibri", 9f, System.Drawing.FontStyle.Regular);
                invDaysSerie.Appearance.TextAppearance.TextProperties.Color = System.Drawing.Color.Black;
                invDaysSerie.AddItem((double)totalSaleSameStoreCY.InvDays, totalSaleSameStoreCY.InvDays.ToString("N0"));
                invDaysSerie.AddItem((double)totalSaleSameStorePY.InvDays, totalSaleSameStorePY.InvDays.ToString("N0"));
                inventoryChart.AddChartSeries(invDaysSerie);

                inventoryChart.PlotArea.XAxis.AddItem(string.Format("{0} CY", rangeReview.Title));
                inventoryChart.PlotArea.XAxis.AddItem(string.Format("{0} PY", rangeReview.Title));

                Image inventoryChartImage = Image.GetInstance(inventoryChart.GetBitmap(), BaseColor.WHITE);
                inventoryChartImage.Alignment = Image.ALIGN_CENTER;
                document.Add(inventoryChartImage);

                document.Add(new Paragraph(" "));

                List inventoryInsights = new List(List.UNORDERED, 30f);
                inventoryInsights.SetListSymbol("\u2022");
                inventoryInsights.IndentationLeft = 60f;
                inventoryInsights.Add(new ListItem("Inventory Insights:", font13bold));

                List sublist = new List(List.UNORDERED, 30f);
                sublist.SetListSymbol("\u2022");

                growth = totalSaleSameStorePY.InventoryCost != 0 ? totalSaleSameStoreCY.InventoryCost / totalSaleSameStorePY.InventoryCost - 1 : 0;
                string change = "higher";
                if (growth < 0)
                {
                    change = "lower";
                    growth = growth * (-1); //Solo para hacerlo positivo.
                }
                sublist.Add(new ListItem(string.Format("Inventory level is {0} {1} than in the previous year.", growth.ToString("P1"), change), font12));

                var declinedCategories = growthCYvsPY.Where(x => x.InventoryGrowth < 0);
                var declinedCatsTop3 = declinedCategories.OrderBy(x => x.InventoryGrowth).Take(3).ToArray();
                string str;
                if (declinedCategories.Count() > 0)
                {
                    str = string.Format("{0} of {1} categories have experienced a decline in their inventory value, among the main ones are: ", declinedCategories.Count(), growthCYvsPY.Count);
                    for (int i = 0; i < declinedCatsTop3.Count(); i++)
                    {
                        str += string.Format("{0} ({1})"
                                , declinedCatsTop3[i].CY.Category
                                , ((declinedCatsTop3[i].CY.InventoryCost - declinedCatsTop3[i].PY.InventoryCost) * -1).ToString("C0"));

                        if (i == declinedCatsTop3.Count() - 2)
                            str += " and ";
                        else if (i < declinedCatsTop3.Count() - 1)
                            str += ", ";
                    }
                }
                else
                {
                    str = "No Categories have experienced a decline in their inventory value";
                }
                sublist.Add(new ListItem(str, font12));

                var increasedCatsTop3 = growthCYvsPY.Where(x => x.InventoryGrowth > 0).OrderByDescending(x => x.InventoryGrowth).Take(3).ToArray();
                decimal increasedTotal = 0;
                if (increasedCatsTop3.Count() > 0)
                {
                    str = "Among the categories that increased their Inventories are: ";
                    for (int i = 0; i < increasedCatsTop3.Count(); i++)
                    {
                        str += increasedCatsTop3[i].CY.Category;

                        if (i == increasedCatsTop3.Count() - 2)
                            str += " and ";
                        else if (i < increasedCatsTop3.Count() - 1)
                            str += ", ";

                        increasedTotal += increasedCatsTop3[i].CY.InventoryCost - increasedCatsTop3[i].PY.InventoryCost;
                    }
                    str += string.Format(" (Together {0})", increasedTotal.ToString("C0"));
                }
                else
                {
                    str = "No categories increased their Inventories.";
                }
                sublist.Add(new ListItem(str, font12));

                var decreasedInvDays = growthCYvsPY.Where(x => x.CY.InvDays < x.PY.InvDays);
                if (decreasedInvDays.Count() > 0)
                {
                    sublist.Add(new ListItem(string.Format("{0} categories have decreased the number of inventory days due to an improved stock management.", decreasedInvDays.Count()), font12));
                }
                else
                {
                    sublist.Add(new ListItem("No categories have decreased the number of inventory days.", font12));
                }

                var increasedInvDays = growthCYvsPY.Where(x => x.CY.InvDays > x.PY.InvDays).ToArray();
                str = string.Empty;
                for (int i = 0; i < increasedInvDays.Count(); i++)
                {
                    str += increasedInvDays[i].CY.Category;

                    if (i == increasedInvDays.Count() - 2)
                        str += " and ";
                    else if (i < increasedInvDays.Count() - 1)
                        str += ", ";
                }
                if (!string.IsNullOrEmpty(str))
                    sublist.Add(new ListItem(str + " should be monitored due to an increase in the number of inventory days.", font12));

                inventoryInsights.Add(sublist);
                document.Add(inventoryInsights);

                #endregion

                #endregion

                #region Product Range Analysis highlights /Main Indicators - Summary

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                caratula2 = new Paragraph();
                caratula2.SpacingBefore = 160f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.MultipliedLeading = 2.5f;
                caratula2.Add(new Paragraph("Product Range Analysis Highlights", font30));
                caratula2.Add(new Paragraph("Main Indicators - Summary", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Main Indicators Summary - Average Store
                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Main Indicators Summary - Average Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable averageStoreTable = new PdfPTable(new float[] { 2f, 20f, 9f, 9f, 6f, 6f, 8f, 8f, 5f, 5f, 5f, 5f });
                averageStoreTable.WidthPercentage = 95;
                averageStoreTable.HeaderRows = 4;
                averageStoreTable.FooterRows = 2;
                emptyTableCell.Colspan = 12;

                averageStoreTable.AddCell(emptyTableCell);

                averageStoreTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                averageStoreTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                averageStoreTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                averageStoreTable.AddCell(new Phrase("#", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("Category", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("Sales", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("GIM", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("# SKUs Analyzed", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("% SKUs with 80% of sales", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("Hurdle Rate", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("Average Price", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("# SKUs below HR", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("# SKUs in bottom 5%", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("# SKUs to De-list", font10boldWhite));
                averageStoreTable.AddCell(new Phrase("% Sales of De-list SKUs", font10boldWhite));

                averageStoreTable.AddCell(emptyTableCell);
                averageStoreTable.AddCell(emptyTableCell);

                averageStoreTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                rank = 1;
                prevAcum = 0;
                acum = 0;
                decimal hurdleRate = 0;
                decimal avgPrice = 0;
                int skusBelowHR = 0;
                int skusToDelist = 0;
                decimal delistedSales = 0;
                decimal delistedSalesPerc = 0;
                decimal skus80SalesPerc = 0;
                decimal totalSkusBottom5 = 0;

                //Calculo el Bottom 5% total
                decimal totalAcum = 0;
                foreach (var paretoItem in paretoItems.Where(x => !x.IsDeletedRangeReview && x.Sales != 0).OrderByDescending(x => x.Sales))
                {
                    totalAcum += paretoItem.Sales;

                    if ((totalSaleAverageStoreCY.Sales != 0 ? totalAcum / totalSaleAverageStoreCY.Sales : 0) >= 0.95m)
                    {
                        totalSkusBottom5++;
                    }
                }

                foreach (var categoryItem in categorySalesAverageStore.Where(x => !x.IsPriorYear).OrderByDescending(x => x.GM))
                {
                    prevAcum = acum;
                    acum += categoryItem.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        averageStoreTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        averageStoreTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    averageStoreTable.AddCell(new Phrase(rank.ToString(), font10));

                    averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    averageStoreTable.AddCell(new Phrase(categoryItem.Category, font10));

                    averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    averageStoreTable.AddCell(new Phrase(categoryItem.Sales.ToString("C2"), font10));

                    averageStoreTable.AddCell(new Phrase(categoryItem.GM.ToString("C2"), font10));

                    averageStoreTable.AddCell(new Phrase(categoryItem.SKUs.ToString("N0"), font10));

                    paretoAcum = 0;
                    paretoPrevAcum = 0;
                    skus80Sales = 0;
                    skusBottom5 = 0;
                    decimal totalCategorySales = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Category == categoryItem.Category).Sum(x => x.Sales);
                    //Loopeo solo los skus con ventas.
                    foreach (var paretoItem in paretoItems.Where(x => !x.IsDeletedRangeReview && x.Category == categoryItem.Category && x.Sales != 0).OrderByDescending(x => x.Sales))
                    {
                        paretoPrevAcum = paretoAcum;
                        paretoAcum += totalCategorySales != 0 ? paretoItem.Sales / totalCategorySales : 0;

                        if (paretoPrevAcum < 0.8m)
                        {
                            skus80Sales++;
                        }
                        else if (paretoPrevAcum >= 0.95m)
                        {
                            skusBottom5++;
                        }
                    }

                    skus80SalesPerc = categoryItem.SKUs != 0 ? skus80Sales / categoryItem.SKUs : 0;
                    averageStoreTable.AddCell(new Phrase(skus80SalesPerc.ToString("P1"), font10));

                    hurdleRate = categoryItem.SKUs != 0 ? categoryItem.Sales / categoryItem.SKUs : 0;
                    averageStoreTable.AddCell(new Phrase(hurdleRate.ToString("C0"), font10));

                    avgPrice = categoryItem.Units != 0 ? categoryItem.Sales / categoryItem.Units : 0;
                    averageStoreTable.AddCell(new Phrase(avgPrice.ToString("C2"), font10));

                    skusBelowHR = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Category == categoryItem.Category && x.Sales < hurdleRate).Count();
                    averageStoreTable.AddCell(new Phrase(skusBelowHR.ToString("N0"), font10));

                    averageStoreTable.AddCell(new Phrase(skusBottom5.ToString("N0"), font10));

                    skusToDelist = paretoItems.Where(x => !x.IsDeletedRangeReview && x.Category == categoryItem.Category && x.Delist).Count(); 
                    averageStoreTable.AddCell(new Phrase(skusToDelist.ToString("N0"), font10));

                    delistedSales = categorySalesAverageStoreDelist.Where(x => !x.IsPriorYear && x.Category == categoryItem.Category).Sum(x => x.Sales);
                    delistedSalesPerc = categoryItem.Sales != 0 ? delistedSales / categoryItem.Sales : 0;
                    averageStoreTable.AddCell(new Phrase(delistedSalesPerc.ToString("P1"), font10));

                    rank++;
                }

                averageStoreTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                averageStoreTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                averageStoreTable.AddCell(" ");

                averageStoreTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                averageStoreTable.DefaultCell.Border = PdfPCell.BOX;

                averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                averageStoreTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                averageStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                averageStoreTable.AddCell(new Phrase(categorySalesAverageStore.Where(x => !x.IsPriorYear).Sum(x => x.Sales).ToString("C0"), font10bold));
                averageStoreTable.AddCell(new Phrase(categorySalesAverageStore.Where(x => !x.IsPriorYear).Sum(x => x.GM).ToString("C0"), font10bold));
                averageStoreTable.AddCell(new Phrase(categorySalesAverageStore.Where(x => !x.IsPriorYear).Sum(x => x.SKUs).ToString("N0"), font10bold));

                averageStoreTable.AddCell(new Phrase(skus80SalesPercTotal.ToString("P1"), font10bold));

                decimal totalHR = totalSaleAverageStoreCY.SKUs != 0 ? totalSaleAverageStoreCY.Sales / totalSaleAverageStoreCY.SKUs : 0;
                averageStoreTable.AddCell(new Phrase(totalHR.ToString("C0"), font10bold));

                decimal totalAvgPrice = totalSaleAverageStoreCY.Units != 0 ? totalSaleAverageStoreCY.Sales / totalSaleAverageStoreCY.Units : 0;
                averageStoreTable.AddCell(new Phrase(totalAvgPrice.ToString("C2"), font10bold));

                averageStoreTable.AddCell(new Phrase(paretoItems.Where(x => !x.IsDeletedRangeReview && x.Sales < totalHR).Count().ToString("N0"), font10bold));

                averageStoreTable.AddCell(new Phrase(totalSkusBottom5.ToString("N0"), font10bold));

                averageStoreTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.SKUs.ToString("N0"), font10bold));

                decimal delistedSalesShare = totalSalesAverageStoreDelistCY.Sales / totalSaleAverageStoreCY.Sales;
                averageStoreTable.AddCell(new Phrase(delistedSalesShare.ToString("P1"), font10bold));

                averageStoreTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                averageStoreTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                averageStoreTable.AddCell(" ");

                document.Add(averageStoreTable);
                #endregion

                #region SKUs Benchmarking - Average Store
                ((PageEvent)writer.PageEvent).Title = "Product Range Analysis Highlights";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "SKUs Benchmarking - Average Store";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                List<HistoryDetail> historyDetailsPY = null;
                List<SalesCategoryComparison> historyDetails1 = null;
                List<SalesCategoryComparison> historyDetails2 = null;
                List<SalesCategoryComparison> historyDetails3 = null;

                if (rangeReview.PYHistoryId.HasValue)
                {
                    var rows = HistoryDetailsRepository.Select(x => x.HistoryId == rangeReview.PYHistoryId.Value);
                    historyDetailsPY = rows.ConvertAll<HistoryDetail>(c => new HistoryDetail(c));
                }

                countColumns = 0;
                foreach (var benchmark in benchmarks)
                {
                    List<SalesCategoryComparisonRow> columnRows;
                    if (benchmark.HistoryGroupId.HasValue)
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparisonHistoryBenchmark(rangeReviewId, 0, benchmark.HistoryGroupId.Value, false, false).ToList();
                    }
                    else
                    {
                        columnRows = ReportsRepository.GetSalesCategoryComparison(rangeReviewId, 0, benchmark.StoreId, benchmark.StoreGroupId).ToList();
                    }

                    if (columnRows.Count > 0)
                    {
                        List<SalesCategoryComparison> salesColumn = columnRows.ConvertAll<SalesCategoryComparison>(c => new SalesCategoryComparison(c));
                        switch (countColumns)
                        {
                            case 0:
                                historyDetails1 = salesColumn;
                                break;
                            case 1:
                                historyDetails2 = salesColumn;
                                break;
                            case 2:
                                historyDetails3 = salesColumn;
                                break;
                        }
                        countColumns++;
                    }
                }

                countColumns = (countColumns * 2) + 3;
                if (totalSaleSameStorePY != null)
                {
                    countColumns = countColumns + 2;
                }

                //Genero una tabla con datos
                columnRelativeWidths = new float[countColumns];
                relativeWidth = 100f / countColumns;
                for (int i = 0; i < countColumns; i++)
                {
                    if (i == 0)
                    {
                        columnRelativeWidths.SetValue(relativeWidth / 3, i);
                    }
                    else if (i == 1)
                    {
                        columnRelativeWidths.SetValue(relativeWidth * 3, i);
                    }
                    else
                    {
                        columnRelativeWidths.SetValue(relativeWidth, i);
                    }
                }

                PdfPTable skusBenchmarkTable = new PdfPTable(columnRelativeWidths);
                skusBenchmarkTable.WidthPercentage = 95;
                skusBenchmarkTable.HeaderRows = 5;
                skusBenchmarkTable.FooterRows = 2;
                emptyTableCell.Colspan = countColumns;

                skusBenchmarkTable.AddCell(emptyTableCell);

                skusBenchmarkTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                skusBenchmarkTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                skusBenchmarkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                skusBenchmarkTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                skusBenchmarkTable.DefaultCell.Rowspan = 2;
                skusBenchmarkTable.AddCell(new Phrase("#", font10boldWhite));
                skusBenchmarkTable.AddCell(new Phrase("Category", font10boldWhite));

                skusBenchmarkTable.DefaultCell.Rowspan = 1;
                skusBenchmarkTable.DefaultCell.Colspan = countColumns - 2;
                skusBenchmarkTable.AddCell(new Phrase("Skus with Sales", font10boldWhite));

                skusBenchmarkTable.DefaultCell.Colspan = 1;
                skusBenchmarkTable.AddCell(new Phrase(rangeReview.Title, font10boldWhite));

                if (totalSaleSameStorePY != null)
                {
                    skusBenchmarkTable.AddCell(new Phrase(rangeReview.Title + " PY", font10boldWhite));
                }

                if (historyDetails1 != null && historyDetails1.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(historyDetails1.First().Title, font10boldWhite));
                }

                if (historyDetails2 != null && historyDetails2.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(historyDetails2.First().Title, font10boldWhite));
                }

                if (historyDetails3 != null && historyDetails3.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(historyDetails3.First().Title, font10boldWhite));
                }

                if (totalSaleSameStorePY != null)
                {
                    skusBenchmarkTable.AddCell(new Phrase("Delta  PY", font10boldWhite));
                }

                if (historyDetails1 != null && historyDetails1.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase("Delta " + historyDetails1.First().Title, font10boldWhite));
                }

                if (historyDetails2 != null && historyDetails2.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase("Delta " + historyDetails2.First().Title, font10boldWhite));
                }

                if (historyDetails3 != null && historyDetails3.Count > 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase("Delta " + historyDetails3.First().Title, font10boldWhite));
                }

                skusBenchmarkTable.AddCell(emptyTableCell);
                skusBenchmarkTable.AddCell(emptyTableCell);

                skusBenchmarkTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                skusBenchmarkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                rank = 1;
                prevAcum = 0;
                acum = 0;
                decimal totalHistoryPYSKUs = 0;
                decimal totalHistoryHistory1SKUs = 0;
                decimal totalHistoryHistory2SKUs = 0;
                decimal totalHistoryHistory3SKUs = 0;

                foreach (var item in categorySalesAverageStore.Where(x => !x.IsPriorYear).OrderByDescending(x => x.GM))
                {
                    prevAcum = acum;
                    acum += item.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        skusBenchmarkTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        skusBenchmarkTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    skusBenchmarkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    skusBenchmarkTable.AddCell(new Phrase(rank.ToString(), font10));

                    skusBenchmarkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    skusBenchmarkTable.AddCell(new Phrase(item.Category, font10));

                    skusBenchmarkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    skusBenchmarkTable.AddCell(new Phrase(item.SKUs.ToString("N0"), font10));

                    //PY
                    decimal deltaPY = 0;
                    if (historyDetailsPY != null)
                    {
                        var py = historyDetailsPY.Where(x => x.CategoryId == item.CategoryId).FirstOrDefault();
                        if (py != null && py.SKUsWithSales.HasValue && py.SKUsWithSales.Value != 0)
                        {
                            skusBenchmarkTable.AddCell(new Phrase(py.SKUsWithSales.Value.ToString("N0"), font10));
                            deltaPY = (decimal)item.SKUs / py.SKUsWithSales.Value - 1;
                            totalHistoryPYSKUs += py.SKUsWithSales.Value;
                        }
                        else
                        {
                            skusBenchmarkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    //History1
                    decimal deltaHistory1 = 0;
                    if (historyDetails1 != null)
                    {
                        var history1 = historyDetails1.Where(x => x.CategoryId == item.CategoryId).FirstOrDefault();
                        
                        if (history1 != null && history1.SKUs != 0)
                        {
                            skusBenchmarkTable.AddCell(new Phrase(history1.SKUs.ToString("N0"), font10));
                            deltaHistory1 = (decimal)item.SKUs / history1.SKUs - 1;
                            totalHistoryHistory1SKUs += history1.SKUs;
                        }
                        else
                        {
                            skusBenchmarkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    //History2
                    decimal deltaHistory2 = 0;
                    if (historyDetails2 != null)
                    {
                        var history2 = historyDetails2.Where(x => x.CategoryId == item.CategoryId).FirstOrDefault();
                        if (history2 != null && history2.SKUs != 0)
                        {
                            skusBenchmarkTable.AddCell(new Phrase(history2.SKUs.ToString("N0"), font10));
                            deltaHistory2 = (decimal)item.SKUs / history2.SKUs - 1;
                            totalHistoryHistory2SKUs += history2.SKUs;
                        }
                        else
                        {
                            skusBenchmarkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    //History3
                    decimal deltaHistory3 = 0;
                    if (historyDetails3 != null)
                    {
                        var history3 = historyDetails3.Where(x => x.CategoryId == item.CategoryId).FirstOrDefault();
                        if (history3 != null && history3.SKUs != 0)
                        {
                            skusBenchmarkTable.AddCell(new Phrase(history3.SKUs.ToString("N0"), font10));
                            deltaHistory3 = (decimal)item.SKUs / history3.SKUs - 1;
                            totalHistoryHistory3SKUs += history3.SKUs;
                        }
                        else
                        {
                            skusBenchmarkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    if (historyDetailsPY != null)
                    {
                        skusBenchmarkTable.AddCell(new Phrase(deltaPY.ToString("P1"), font10));
                    }
                    if (historyDetails1 != null)
                    {
                        skusBenchmarkTable.AddCell(new Phrase(deltaHistory1.ToString("P1"), font10));
                    }
                    if (historyDetails2 != null)
                    {
                        skusBenchmarkTable.AddCell(new Phrase(deltaHistory2.ToString("P1"), font10));
                    }
                    if (historyDetails3 != null)
                    {
                        skusBenchmarkTable.AddCell(new Phrase(deltaHistory3.ToString("P1"), font10));
                    }

                    rank++;
                }

                skusBenchmarkTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                skusBenchmarkTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                skusBenchmarkTable.AddCell(" ");

                skusBenchmarkTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                skusBenchmarkTable.DefaultCell.Border = PdfPCell.BOX;

                skusBenchmarkTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                skusBenchmarkTable.AddCell(new Phrase(totalSaleAverageStoreCY.SKUs.ToString("N0"), font10bold));
                if (totalHistoryPYSKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(totalHistoryPYSKUs.ToString("N0"), font10bold));
                }
                if (totalHistoryHistory1SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(totalHistoryHistory1SKUs.ToString("N0"), font10bold));
                }
                if (totalHistoryHistory2SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(totalHistoryHistory2SKUs.ToString("N0"), font10bold));
                }
                if (totalHistoryHistory3SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase(totalHistoryHistory3SKUs.ToString("N0"), font10bold));
                }

                if (totalHistoryPYSKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase((totalSaleAverageStoreCY.SKUs / totalHistoryPYSKUs - 1).ToString("P0"), font10bold));
                }
                if (totalHistoryHistory1SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase((totalSaleAverageStoreCY.SKUs / totalHistoryHistory1SKUs - 1).ToString("P0"), font10bold));
                }
                if (totalHistoryHistory2SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase((totalSaleAverageStoreCY.SKUs / totalHistoryHistory2SKUs - 1).ToString("P0"), font10bold));
                }
                if (totalHistoryHistory3SKUs != 0)
                {
                    skusBenchmarkTable.AddCell(new Phrase((totalSaleAverageStoreCY.SKUs / totalHistoryHistory3SKUs - 1).ToString("P0"), font10bold));
                }

                document.Add(skusBenchmarkTable);

                #endregion


                #endregion
                
                #region Back Up

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;

                document.NewPage();

                caratula2 = new Paragraph();
                caratula2.SpacingBefore = 160f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.MultipliedLeading = 2.5f;
                caratula2.Add(new Paragraph("Back Up", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Sample Validation - Store Distribution
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sample Validation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Store Distribution";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();


                layoutTable = new PdfPTable(new float[] { 60f, 40f });
                layoutTable.WidthPercentage = 100;
                layoutTable.SpacingBefore = 20f;
                layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.DefaultCell.Padding = 10;


                var salesByStore = ReportsRepository.GetSalesCategoryComparisonByStore(rangeReview.Id, null, 2);

                #region NETWORK STORES
                //NETWORK STORES
                //Paragraph tableTitle = new Paragraph(string.Format("Network: {0} Stores", salesByStore.Select(x => x.StoreCode).Distinct().Count()), font13blue);
                //tableTitle.SpacingBefore = 15f;
                //document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);

                //TODO: COMMENTS
                //layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                //layoutTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                //layoutTable.DefaultCell.Rowspan = 7;

                //layoutTable.AddCell("ESPACIO PARA COMENTARIOS...");

                //TODO: Hacer que la apertura la levante de la configuracion. Ahora queda hardcoded apertura x SEL.
                var attributes = salesByStore.Select(x => x.SEL).Distinct();

                PdfPTable networkTable = new PdfPTable(attributes.Count() + 2);
                networkTable.SpacingBefore = 10f;
                networkTable.HeaderRows = 2;
                networkTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                networkTable.DefaultCell.BorderWidthBottom = 1.5f;
                networkTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                networkTable.DefaultCell.Colspan = attributes.Count() + 2;
                networkTable.AddCell(new Phrase(string.Format("Network: {0} Stores", salesByStore.Select(x => x.StoreCode).Distinct().Count()), font13blue));
                networkTable.DefaultCell.Colspan = 1;

                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                networkTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    networkTable.AddCell(new Phrase(att, font10));
                }

                networkTable.AddCell(new Phrase("Total", font10));

                networkTable.DefaultCell.BorderWidthBottom = 1;
                networkTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);

                //Genera filas
                int totalStoresSegment = 0;
                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    networkTable.AddCell(new Phrase(format, font10));

                    networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoresSegment = salesByStore.Where(x => x.Format == format && x.SEL == att)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                        if (totalStoresSegment != 0)
                        {
                            networkTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                        }
                        else
                        {
                            networkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    totalStoresSegment = salesByStore.Where(x => x.Format == format)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                    if (totalStoresSegment != 0)
                    {
                        networkTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                    }
                    else
                    {
                        networkTable.AddCell(new Phrase(string.Empty));
                    }
                }

                networkTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                networkTable.AddCell(new Phrase("Total", font10));
                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    totalStoresSegment = salesByStore.Where(x => x.SEL == att)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                    if (totalStoresSegment != 0)
                    {
                        networkTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                    }
                    else
                    {
                        networkTable.AddCell(new Phrase(string.Empty));
                    }
                }
                networkTable.AddCell(new Phrase(salesByStore.Select(x => x.StoreCode).Distinct().Count().ToString("N0"), font10));

                document.Add(networkTable);
                //layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //layoutTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                //layoutTable.DefaultCell.Rowspan = 1;
                //layoutTable.AddCell(networkTable); 
                #endregion

                #region RANGE REVIEW STORES
                //RANGE REVIEW STORES
                List<int> rrStores = RangeReviewDomain.GetRangeReviewStores(rangeReview).Where(x => !x.IsExcluded).Select(x => x.StoreId).ToList();
                var rangeStoresSales = salesByStore.Where(x => rrStores.Contains(x.StoreId));

                //tableTitle = new Paragraph(string.Format("Range Review: {0} Stores", rangeStoresSales.Select(x => x.StoreId).Distinct().Count()), font13blue);
                //tableTitle.SpacingBefore = 25f;
                //tableTitle.IndentationLeft = 60f;
                ////document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);


                PdfPTable rangeTable = new PdfPTable(attributes.Count() + 2);
                rangeTable.SpacingBefore = 10f;
                rangeTable.HeaderRows = 1;
                rangeTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                rangeTable.DefaultCell.BorderWidthBottom = 1.5f;
                rangeTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                rangeTable.DefaultCell.Colspan = attributes.Count() + 2;
                rangeTable.AddCell(new Phrase(string.Format("Range Review: {0} Stores", rangeStoresSales.Select(x => x.StoreId).Distinct().Count()), font13blue));
                rangeTable.DefaultCell.Colspan = 1;

                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                rangeTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    rangeTable.AddCell(new Phrase(att, font10));
                }

                rangeTable.AddCell(new Phrase("Total", font10));

                rangeTable.DefaultCell.BorderWidthBottom = 1;
                rangeTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);


                //Genera filas
                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    rangeTable.AddCell(new Phrase(format, font10));

                    rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoresSegment = rangeStoresSales.Where(x => x.Format == format && x.SEL == att)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                        if (totalStoresSegment != 0)
                        {
                            rangeTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                        }
                        else
                        {
                            rangeTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    totalStoresSegment = rangeStoresSales.Where(x => x.Format == format)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                    if (totalStoresSegment != 0)
                    {
                        rangeTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                    }
                    else
                    {
                        rangeTable.AddCell(new Phrase(string.Empty));
                    }
                }

                rangeTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                rangeTable.AddCell(new Phrase("Total", font10));
                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    totalStoresSegment = rangeStoresSales.Where(x => x.SEL == att)
                                                                    .Select(x => x.StoreCode)
                                                                    .Distinct()
                                                                    .Count();
                    if (totalStoresSegment != 0)
                    {
                        rangeTable.AddCell(new Phrase(totalStoresSegment.ToString("N0"), font10));
                    }
                    else
                    {
                        rangeTable.AddCell(new Phrase(string.Empty));
                    }
                }
                rangeTable.AddCell(new Phrase(rangeStoresSales.Select(x => x.StoreCode).Distinct().Count().ToString("N0"), font10));

                document.Add(rangeTable);
                //layoutTable.AddCell(rangeTable); 
                #endregion

                #region NETWORK STORES - SALES DISTRIBUTION

                //NETWORK STORES - SALES DISTRIBUTION                                
                int totalStores = salesByStore.Select(x => x.StoreCode).Distinct().Count();
                //tableTitle = new Paragraph(string.Format("Network: {0} Stores - Sales Distribution", totalStores), font13blue);
                //tableTitle.SpacingBefore = 15f;
                //tableTitle.IndentationLeft = 60f;

                ////document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);

                PdfPTable distributionTable = new PdfPTable(attributes.Count() + 2);
                distributionTable.SpacingBefore = 10f;
                distributionTable.HeaderRows = 1;
                distributionTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                distributionTable.DefaultCell.BorderWidthBottom = 1.5f;
                distributionTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                distributionTable.DefaultCell.Colspan = attributes.Count() + 2;
                distributionTable.AddCell(new Phrase(string.Format("Network: {0} Stores - Sales Distribution", totalStores), font13blue));
                distributionTable.DefaultCell.Colspan = 1;

                distributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                distributionTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    distributionTable.AddCell(new Phrase(att, font10));
                }

                distributionTable.AddCell(new Phrase("Total", font10));

                distributionTable.DefaultCell.BorderWidthBottom = 1;
                distributionTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);


                //Genera filas
                decimal totalStoreSales = salesByStore.Sum(x => x.Sales);
                decimal totalStoreSalesSegment = 0;
                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    distributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    distributionTable.AddCell(new Phrase(format, font10));

                    distributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoreSalesSegment = salesByStore.Where(x => x.Format == format && x.SEL == att).Sum(x => x.Sales);

                        distributionTable.AddCell(new Phrase(totalStoreSalesSegment != 0 && totalStoreSales != 0 ? (totalStoreSalesSegment / totalStoreSales)
                                                                    .ToString("P0") : string.Empty, font10));
                    }

                    totalStoreSalesSegment = salesByStore.Where(x => x.Format == format).Sum(x => x.Sales);
                    distributionTable.AddCell(new Phrase(totalStoreSalesSegment != 0 && totalStoreSales != 0 ? (totalStoreSalesSegment / totalStoreSales)
                                                                    .ToString("P0") : string.Empty, font10));
                }

                distributionTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                distributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                distributionTable.AddCell(new Phrase("Total", font10));
                distributionTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    totalStoreSalesSegment = salesByStore.Where(x => x.SEL == att).Sum(x => x.Sales);

                    distributionTable.AddCell(new Phrase(totalStoreSalesSegment != 0 && totalStoreSales != 0 ? (totalStoreSalesSegment / totalStoreSales)
                                                                .ToString("P0") : string.Empty, font10));

                }
                distributionTable.AddCell(new Phrase("100%", font10));

                document.Add(distributionTable);
                //layoutTable.AddCell(distributionTable);
                //layoutTable.AddCell(" "); 
                #endregion

                document.Add(layoutTable);


                #endregion

                #region Sample Validation - Store Distribution 2
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sample Validation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Store Distribution";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                //layoutTable = new PdfPTable(new float[] { 60f, 40f });
                //layoutTable.WidthPercentage = 100;
                //layoutTable.SpacingBefore = 20f;
                //layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                //layoutTable.DefaultCell.Padding = 10;

                #region NETWORK STORES
                //NETWORK STORES
                //tableTitle = new Paragraph(string.Format("Network: {0} Stores", salesByStore.Select(x => x.StoreCode).Distinct().Count()), font13blue);
                //tableTitle.SpacingBefore = 15f;
                //tableTitle.IndentationLeft = 60f;
                ////document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);

                //TODO: COMMENTS
                //layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                //layoutTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                //layoutTable.DefaultCell.Rowspan = 7;
                //layoutTable.AddCell("ESPACIO PARA COMENTARIOS...");

                //TODO: Hacer que la apertura la levante de la configuracion. Ahora queda hardcoded apertura x SEL.
                networkTable = new PdfPTable(attributes.Count() + 2);
                networkTable.SpacingBefore = 10f;
                networkTable.HeaderRows = 1;
                networkTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                networkTable.DefaultCell.BorderWidthBottom = 1.5f;
                networkTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                networkTable.DefaultCell.Colspan = attributes.Count() + 2;
                networkTable.AddCell(new Phrase(string.Format("Network: {0} Stores", salesByStore.Select(x => x.StoreCode).Distinct().Count()), font13blue));
                networkTable.DefaultCell.Colspan = 1;

                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                networkTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    networkTable.AddCell(new Phrase(att, font10));
                }

                networkTable.AddCell(new Phrase("Total", font10));

                networkTable.DefaultCell.BorderWidthBottom = 1;
                networkTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);

                //Genera filas

                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    networkTable.AddCell(new Phrase(format, font10));

                    networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoresSegment = salesByStore.Where(x => x.Format == format && x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                        if (totalStoresSegment != 0)
                        {
                            networkTable.AddCell(new Phrase((salesByStore.Where(x => x.Format == format && x.SEL == att)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                        }
                        else
                        {
                            networkTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    totalStoresSegment = salesByStore.Where(x => x.Format == format).Select(x => x.StoreCode).Distinct().Count();
                    if (totalStoresSegment != 0)
                    {
                        networkTable.AddCell(new Phrase((salesByStore.Where(x => x.Format == format)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                    }
                    else
                    {
                        networkTable.AddCell(new Phrase(string.Empty));
                    }
                }

                networkTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                networkTable.AddCell(new Phrase("Total", font10));
                networkTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    if (totalStoresSegment != 0)
                    {
                        totalStoresSegment = salesByStore.Where(x => x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                        networkTable.AddCell(new Phrase((salesByStore.Where(x => x.SEL == att)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                    }
                    else
                    {
                        networkTable.AddCell(new Phrase(string.Empty));
                    }
                }
                networkTable.AddCell(new Phrase((salesByStore.Sum(x => x.Sales) / totalStores).ToString("C0"), font10));

                document.Add(networkTable);

                //layoutTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //layoutTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                //layoutTable.DefaultCell.Rowspan = 1;
                //layoutTable.AddCell(networkTable); 
                #endregion

                #region RANGE REVIEW STORES
                //RANGE REVIEW STORES
                //tableTitle = new Paragraph(string.Format("Range Review: {0} Stores", rangeStoresSales.Select(x => x.StoreId).Distinct().Count()), font13blue);
                //tableTitle.SpacingBefore = 25f;
                //tableTitle.IndentationLeft = 60f;
                ////document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);

                totalStores = rangeStoresSales.Select(x => x.StoreId).Distinct().Count();

                rangeTable = new PdfPTable(attributes.Count() + 2);
                rangeTable.SpacingBefore = 25f;
                rangeTable.HeaderRows = 1;
                rangeTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                rangeTable.DefaultCell.BorderWidthBottom = 1.5f;
                rangeTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                rangeTable.DefaultCell.Colspan = attributes.Count() + 2;
                rangeTable.AddCell(new Phrase(string.Format("Range Review: {0} Stores", totalStores), font13blue));
                rangeTable.DefaultCell.Colspan = 1;

                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                rangeTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    rangeTable.AddCell(new Phrase(att, font10));
                }

                rangeTable.AddCell(new Phrase("Total", font10));

                rangeTable.DefaultCell.BorderWidthBottom = 1;
                rangeTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);

                //Genera filas
                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    rangeTable.AddCell(new Phrase(format, font10));

                    rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoresSegment = rangeStoresSales.Where(x => x.Format == format && x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                        if (totalStoresSegment != 0)
                        {
                            rangeTable.AddCell(new Phrase((rangeStoresSales.Where(x => x.Format == format && x.SEL == att)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                        }
                        else
                        {
                            rangeTable.AddCell(new Phrase(string.Empty));
                        }
                    }

                    totalStoresSegment = rangeStoresSales.Where(x => x.Format == format).Select(x => x.StoreCode).Distinct().Count();
                    if (totalStoresSegment != 0)
                    {
                        rangeTable.AddCell(new Phrase((rangeStoresSales.Where(x => x.Format == format)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                    }
                    else
                    {
                        rangeTable.AddCell(new Phrase(string.Empty));
                    }
                }

                rangeTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                rangeTable.AddCell(new Phrase("Total", font10));
                rangeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    totalStoresSegment = rangeStoresSales.Where(x => x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                    if (totalStoresSegment != 0)
                    {
                        rangeTable.AddCell(new Phrase((rangeStoresSales.Where(x => x.SEL == att)
                                                                        .Sum(x => x.Sales) / totalStoresSegment)
                                                                        .ToString("C0"), font10));
                    }
                    else
                    {
                        rangeTable.AddCell(new Phrase(string.Empty));
                    }
                }
                rangeTable.AddCell(new Phrase((rangeStoresSales.Sum(x => x.Sales) / totalStores).ToString("C0"), font10));

                document.Add(rangeTable);
                //layoutTable.AddCell(rangeTable);

                #endregion

                #region DELTA RANGE REVIEW VS NETWORK
                //DELTA RANGE REVIEW VS NETWORK
                //tableTitle = new Paragraph("Delta Range Review vs Network", font13blue);
                //tableTitle.SpacingBefore = 25f;
                //tableTitle.IndentationLeft = 60f;
                ////document.Add(tableTitle);
                //layoutTable.AddCell(tableTitle);


                PdfPTable deltaTable = new PdfPTable(attributes.Count() + 2);
                deltaTable.SpacingBefore = 25f;
                deltaTable.HeaderRows = 1;
                deltaTable.DefaultCell.BorderColor = new BaseColor(193, 208, 205);
                deltaTable.DefaultCell.BorderWidthBottom = 1.5f;
                deltaTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);

                deltaTable.DefaultCell.Colspan = attributes.Count() + 2;
                deltaTable.AddCell(new Phrase("Delta Range Review Panel vs. Network", font13blue));
                deltaTable.DefaultCell.Colspan = 1;

                deltaTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                deltaTable.AddCell(new Phrase("Format", font10));

                foreach (string att in attributes.OrderBy(x => x))
                {
                    deltaTable.AddCell(new Phrase(att, font10));
                }

                deltaTable.AddCell(new Phrase("Total", font10));

                deltaTable.DefaultCell.BorderWidthBottom = 1;
                deltaTable.DefaultCell.BackgroundColor = new BaseColor(255, 255, 203);

                //Genera filas
                decimal rangeValue = 0;
                decimal networkValue = 0;
                foreach (string format in salesByStore.Select(x => x.Format).Distinct())
                {
                    deltaTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    deltaTable.AddCell(new Phrase(format, font10));

                    deltaTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    //Genera columnas
                    

                    foreach (string att in attributes.OrderBy(x => x))
                    {
                        totalStoresSegment = rangeStoresSales.Where(x => x.Format == format && x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                        rangeValue = totalStoresSegment != 0 ? rangeStoresSales.Where(x => x.Format == format && x.SEL == att).Sum(x => x.Sales) / totalStoresSegment : 0;
                        totalStoresSegment = salesByStore.Where(x => x.Format == format && x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                        networkValue = totalStoresSegment != 0 ? salesByStore.Where(x => x.Format == format && x.SEL == att).Sum(x => x.Sales) / totalStoresSegment : 0;

                        deltaTable.AddCell(new Phrase(networkValue != 0 && rangeValue != 0 ? (rangeValue / networkValue - 1).ToString("P0") : string.Empty, font10));
                    }

                    totalStoresSegment = rangeStoresSales.Where(x => x.Format == format).Select(x => x.StoreCode).Distinct().Count();
                    rangeValue = totalStoresSegment != 0 ? rangeStoresSales.Where(x => x.Format == format).Sum(x => x.Sales) / totalStoresSegment : 0;
                    totalStoresSegment = salesByStore.Where(x => x.Format == format).Select(x => x.StoreCode).Distinct().Count();
                    networkValue = totalStoresSegment != 0 ? salesByStore.Where(x => x.Format == format).Sum(x => x.Sales) / totalStoresSegment : 0;

                    deltaTable.AddCell(new Phrase(networkValue != 0 && rangeValue != 0 ? (rangeValue / networkValue - 1).ToString("P0") : string.Empty, font10));
                }

                deltaTable.DefaultCell.BackgroundColor = new BaseColor(192, 192, 192);
                deltaTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                deltaTable.AddCell(new Phrase("Total", font10));
                deltaTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                foreach (string att in attributes.OrderBy(x => x))
                {
                    totalStoresSegment = rangeStoresSales.Where(x => x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                    rangeValue = totalStoresSegment != 0 ? rangeStoresSales.Where(x => x.SEL == att).Sum(x => x.Sales) / totalStoresSegment : 0;
                    totalStoresSegment = salesByStore.Where(x => x.SEL == att).Select(x => x.StoreCode).Distinct().Count();
                    networkValue = totalStoresSegment != 0 ? salesByStore.Where(x => x.SEL == att).Sum(x => x.Sales) / totalStoresSegment : 0;

                    deltaTable.AddCell(new Phrase(networkValue != 0 && rangeValue != 0 ? (rangeValue / networkValue - 1).ToString("P0") : string.Empty, font10));
                }

                totalStoresSegment = rangeStoresSales.Select(x => x.StoreCode).Distinct().Count();
                rangeValue = totalStoresSegment != 0 ? rangeStoresSales.Sum(x => x.Sales) / totalStoresSegment : 0;
                totalStoresSegment = salesByStore.Select(x => x.StoreCode).Distinct().Count();
                networkValue = totalStoresSegment != 0 ? salesByStore.Sum(x => x.Sales) / totalStoresSegment : 0;
                deltaTable.AddCell(new Phrase(networkValue != 0 && rangeValue != 0 ? (rangeValue / networkValue - 1).ToString("P0") : string.Empty, font10));

                document.Add(deltaTable);
                //layoutTable.AddCell(deltaTable);

                //layoutTable.AddCell(" "); 
                #endregion

                //document.Add(layoutTable);

                #endregion

                #region Sample Validation: Average Monthly Sales (%) – Total Network vs. Range Review
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sample Validation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Average Monthly Sales (%) – Total Network vs. Range Review";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                //TODO: Ver como parametrizar las categorias que hay se deberian excluir para algunos reportes.
                var networkCategorySales = from cat in salesByStore
                                           group cat by cat.Category into g
                                           orderby g.Key
                                           select new { Category = g.Key, AverageSales = g.Average(x => x.Sales) };

                var rangeCategorySales = from cat in rangeStoresSales
                                         group cat by cat.Category into g
                                         select new { Category = g.Key, AverageSales = g.Average(x => x.Sales) };

                decimal totalNetwork = networkCategorySales.Sum(x => x.AverageSales);
                decimal totalRange = rangeCategorySales.Sum(x => x.AverageSales);

                PdfPTable averageSalesTable = new PdfPTable(new float[] { 20f, 6f, 6f, 6f });
                averageSalesTable.HeaderRows = 3;
                averageSalesTable.FooterRows = 2;
                averageSalesTable.HorizontalAlignment = Element.ALIGN_LEFT;
                averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                averageSalesTable.DefaultCell.BorderColor = new BaseColor(155, 181, 214);
                emptyTableCell.Colspan = 4;

                //cabecera
                averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                averageSalesTable.AddCell(new Phrase("Category", font10));
                averageSalesTable.AddCell(new Phrase("Network", font10));
                averageSalesTable.AddCell(new Phrase("Range Review", font10));
                averageSalesTable.AddCell(new Phrase("Diff. % Points", font10));
                averageSalesTable.AddCell(emptyTableCell); //footer
                averageSalesTable.AddCell(emptyTableCell);

                List<string> deviationGreaterThanOne = new List<string>();

                if (totalNetwork != 0 && totalRange != 0)
                {
                    decimal valNetwork = 0;
                    decimal valRange = 0;
                    decimal diff = 0;

                    //Recorro network que seria la mas completa
                    foreach (var cat in networkCategorySales)
                    {
                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);//celeste
                        averageSalesTable.AddCell(new Phrase(cat.Category, font10));
                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        valNetwork = cat.AverageSales / totalNetwork;
                        averageSalesTable.AddCell(new Phrase(valNetwork.ToString("P1"), font10));

                        averageSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                        var rangeCat = rangeCategorySales.SingleOrDefault(x => x.Category == cat.Category);
                        valRange = rangeCat != null ? rangeCat.AverageSales / totalRange : 0;
                        averageSalesTable.AddCell(new Phrase(valRange.ToString("P1"), font10));

                        averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 228, 188); //verde
                        diff = valRange - valNetwork;
                        averageSalesTable.AddCell(new Phrase(diff.ToString("P1"), font10));

                        if (diff <= -0.01m || diff >= 0.01m)
                            deviationGreaterThanOne.Add(cat.Category);
                    }

                    averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216); //gris
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    averageSalesTable.AddCell(new Phrase("Total", font10));
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    averageSalesTable.AddCell(new Phrase("100%", font10));
                    averageSalesTable.AddCell(new Phrase("100%", font10));
                    averageSalesTable.AddCell(new Phrase(string.Empty, font10));
                }


                //Cuadro de Comentarios
                List commentsList = new List(List.UNORDERED, 10f);
                commentsList.SetListSymbol("\u2022");
                commentsList.IndentationLeft = 10f;
                commentsList.Add(new ListItem("Range Review panel represents the total universe.", font11));
                string text = "All categories show deviations lower than 1%";
                if (deviationGreaterThanOne.Any())
                {
                    text = "";
                    foreach (string cat in deviationGreaterThanOne.OrderBy(x => x))
                    {
                        text += cat;
                        if (deviationGreaterThanOne.OrderBy(x => x).Last() != cat)
                            text += ", ";
                    }

                    text += " present deviation above 1% while all other categories show deviations lower than 1%";
                }
                commentsList.Add(new ListItem(text, font11));


                layoutTable = new PdfPTable(new float[] { 65f, 35f });
                layoutTable.WidthPercentage = 90;
                layoutTable.SpacingBefore = 20f;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.DefaultCell.Rowspan = 2;
                layoutTable.DefaultCell.PaddingRight = 50f;
                layoutTable.AddCell(averageSalesTable);
                PdfPCell layoutCell = new PdfPCell();
                layoutCell.BackgroundColor = new BaseColor(216, 216, 216);
                layoutCell.Border = PdfPCell.NO_BORDER;
                layoutCell.PaddingBottom = 10f;
                layoutCell.AddElement(commentsList);
                layoutTable.AddCell(layoutCell);
                layoutTable.DefaultCell.Rowspan = 1;
                layoutTable.AddCell(string.Empty);

                document.Add(layoutTable);

                #endregion

                #region Sample Validation: Average Monthly Sales (%) by Store Format – Total Network
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sample Validation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Average Monthly Sales (%) by Store Format – Total Network";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();


                List<float> widths = new List<float> { 20f, 6f }; //Primer y ultima columna.               
                foreach (var sel in salesByStore.Select(x => x.Format).Distinct().OrderBy(x => x)) //Una mas por cada columna
                {
                    widths.Add(6f);
                }

                averageSalesTable = new PdfPTable(widths.ToArray());
                averageSalesTable.HeaderRows = 4;
                averageSalesTable.FooterRows = 2;
                averageSalesTable.HorizontalAlignment = Element.ALIGN_LEFT;
                averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                averageSalesTable.DefaultCell.BorderColor = new BaseColor(155, 181, 214);
                emptyTableCell.Colspan = widths.Count + 2;

                //cabecera
                averageSalesTable.AddCell(emptyTableCell);
                averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                averageSalesTable.AddCell(new Phrase("Category", font10));

                foreach (var format in salesByStore.Select(x => x.Format).Distinct().OrderBy(x => x))
                {
                    averageSalesTable.AddCell(new Phrase(format, font10));
                }

                averageSalesTable.AddCell(new Phrase("Network", font10));
                averageSalesTable.AddCell(emptyTableCell); //footer
                averageSalesTable.AddCell(emptyTableCell);

                if (totalNetwork != 0 && totalRange != 0)
                {
                    decimal networkVal = 0;
                    decimal formatVal = 0;
                    decimal formatTotal = 0;

                    PdfPCell greenCell = new PdfPCell();
                    greenCell.BackgroundColor = new BaseColor(234, 242, 221);
                    greenCell.BorderColor = new BaseColor(155, 181, 214);
                    greenCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    PdfPCell redCell = new PdfPCell();
                    redCell.BackgroundColor = new BaseColor(252, 233, 218);
                    redCell.BorderColor = new BaseColor(155, 181, 214);
                    redCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    Font greenCellFont = new Font(Calibri, 10f, Font.NORMAL, new BaseColor(132, 164, 125));
                    Font redCellFont = new Font(Calibri, 10f, Font.NORMAL, new BaseColor(162, 54, 52));

                    foreach (var cat in networkCategorySales)
                    {
                        averageSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        averageSalesTable.AddCell(new Phrase(cat.Category, font10));

                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        networkVal = cat.AverageSales / totalNetwork;

                        foreach (var format in salesByStore.Select(x => x.Format).Distinct().OrderBy(x => x))
                        {
                            formatTotal = salesByStore.Where(x => x.Format == format).Sum(x => x.Sales);
                            var q = salesByStore.Where(x => x.Format == format && x.Category == cat.Category);
                            formatVal = q.Any() ? (decimal)q.Sum(x => x.Sales) : 0;
                            formatVal = formatTotal != 0 ? formatVal / formatTotal : 0;

                            if (formatVal > networkVal)
                            {
                                greenCell.Phrase = new Phrase(formatVal.ToString("P1"), greenCellFont);
                                averageSalesTable.AddCell(greenCell);
                            }
                            else
                            {
                                redCell.Phrase = new Phrase(formatVal.ToString("P1"), redCellFont);
                                averageSalesTable.AddCell(redCell);
                            }
                        }

                        averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(242, 242, 242);
                        averageSalesTable.AddCell(new Phrase(networkVal.ToString("P1"), font10));
                    }

                    averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    averageSalesTable.AddCell(new Phrase("Total", font10));
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    foreach (var format in salesByStore.Select(x => x.Format).Distinct().OrderBy(x => x))
                    {
                        averageSalesTable.AddCell(new Phrase("100%", font10));
                    }
                    averageSalesTable.AddCell(new Phrase("100%", font10));


                    ////Cuadro de Comentarios
                    //commentsList = new List(List.UNORDERED, 10f);
                    //commentsList.SetListSymbol("\u2022");
                    //commentsList.IndentationLeft = 670f;
                    //commentsList.Add(new ListItem("Top selling categories generate almost 80% of sales in all formats.", font11));


                    layoutTable = new PdfPTable(new float[] { 85f, 15f });
                    layoutTable.WidthPercentage = 90;
                    layoutTable.SpacingBefore = 20f;
                    layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                    layoutTable.AddCell(averageSalesTable);
                    layoutTable.AddCell(string.Empty);

                    document.Add(layoutTable);
                    //document.Add(averageSalesTable);
                }



                #endregion

                #region Sample Validation: Average Monthly Sales (%) by Demographics – Total Network
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Sample Validation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Average Monthly Sales (%) by Demographics – Total Network";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                widths = new List<float> { 20f, 6f }; //Primer y ultima columna.               
                foreach (var sel in salesByStore.Select(x => x.SEL).Distinct().OrderBy(x => x)) //Una mas por cada columna
                {
                    widths.Add(6f);
                }

                averageSalesTable = new PdfPTable(widths.ToArray());
                averageSalesTable.HeaderRows = 3;
                averageSalesTable.FooterRows = 2;
                averageSalesTable.HorizontalAlignment = Element.ALIGN_LEFT;
                averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                averageSalesTable.DefaultCell.BorderColor = new BaseColor(155, 181, 214);
                emptyTableCell.Colspan = widths.Count + 2;

                //cabecera
                averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                averageSalesTable.AddCell(new Phrase("Category", font10));
                foreach (var sel in salesByStore.Select(x => x.SEL).Distinct().OrderBy(x => x))
                {
                    averageSalesTable.AddCell(new Phrase(sel, font10));
                }
                averageSalesTable.AddCell(new Phrase("Network", font10));
                averageSalesTable.AddCell(emptyTableCell); //footer
                averageSalesTable.AddCell(emptyTableCell);

                if (totalNetwork != 0 && totalRange != 0)
                {
                    decimal networkVal = 0;
                    decimal selVal = 0;
                    decimal selTotal = 0;

                    PdfPCell greenCell = new PdfPCell();
                    greenCell.BackgroundColor = new BaseColor(234, 242, 221);
                    greenCell.BorderColor = new BaseColor(155, 181, 214);
                    greenCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    PdfPCell redCell = new PdfPCell();
                    redCell.BackgroundColor = new BaseColor(252, 233, 218);
                    redCell.BorderColor = new BaseColor(155, 181, 214);
                    redCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    Font greenCellFont = new Font(Calibri, 10f, Font.NORMAL, new BaseColor(132, 164, 125));
                    Font redCellFont = new Font(Calibri, 10f, Font.NORMAL, new BaseColor(162, 54, 52));

                    foreach (var cat in networkCategorySales)
                    {
                        averageSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        averageSalesTable.AddCell(new Phrase(cat.Category, font10));

                        averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        networkVal = cat.AverageSales / totalNetwork;

                        foreach (var sel in salesByStore.Select(x => x.SEL).Distinct().OrderBy(x => x))
                        {
                            selTotal = salesByStore.Where(x => x.SEL == sel).Sum(x => x.Sales);
                            var q = salesByStore.Where(x => x.SEL == sel && x.Category == cat.Category);
                            selVal = q.Any() ? (decimal)q.Sum(x => x.Sales) : 0;
                            selVal = selTotal != 0 ? selVal / selTotal : 0;

                            if (selVal > networkVal)
                            {
                                greenCell.Phrase = new Phrase(selVal.ToString("P1"), greenCellFont);
                                averageSalesTable.AddCell(greenCell);
                            }
                            else
                            {
                                redCell.Phrase = new Phrase(selVal.ToString("P1"), redCellFont);
                                averageSalesTable.AddCell(redCell);
                            }
                        }

                        averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(242, 242, 242);
                        averageSalesTable.AddCell(new Phrase(networkVal.ToString("P1"), font10));
                    }

                    averageSalesTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    averageSalesTable.AddCell(new Phrase("Total", font10));
                    averageSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    foreach (var sel in salesByStore.Select(x => x.SEL).Distinct().OrderBy(x => x)) //Una mas por cada columna
                    {
                        averageSalesTable.AddCell(new Phrase("100%", font10));
                    }
                    averageSalesTable.AddCell(new Phrase("100%", font10));


                    //Cuadro de Comentarios
                    commentsList = new List(List.UNORDERED, 10f);
                    commentsList.SetListSymbol("\u2022");
                    commentsList.IndentationLeft = 10f;
                    commentsList.Add(new ListItem("Categories highlighted in red are below total network sales average.", font11));

                    layoutTable = new PdfPTable(new float[] { 65f, 35f });
                    layoutTable.WidthPercentage = 90;
                    layoutTable.SpacingBefore = 20f;
                    layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                    layoutTable.DefaultCell.Rowspan = 2;
                    layoutTable.DefaultCell.PaddingRight = 50f;
                    layoutTable.AddCell(averageSalesTable);
                    layoutCell = new PdfPCell();
                    layoutCell.BackgroundColor = new BaseColor(216, 216, 216);
                    layoutCell.Border = PdfPCell.NO_BORDER;
                    layoutCell.PaddingBottom = 10f;
                    layoutCell.AddElement(commentsList);
                    layoutTable.AddCell(layoutCell);
                    layoutTable.DefaultCell.Rowspan = 1;
                    layoutTable.AddCell(string.Empty);

                    document.Add(layoutTable);
                }


                #endregion

                #region Product Range Analysis Scope
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Product Range Analysis Scope";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                commentsList = new List(List.UNORDERED, 20f);
                commentsList.SetListSymbol("\u2022");
                commentsList.IndentationLeft = 30f;
                commentsList.Add(new ListItem(string.Format("The {0} Product Range Review was run from {1} to {2}, with the following store sample:"
                                                                , rangeReview.Title
                                                                , rangeReview.FirstMonth.ToString("MMMM yyyy")
                                                                , rangeReview.FirstMonth.AddMonths(rangeReview.TotalMonths - 1).ToString("MMMM yyyy")), font14));

                document.Add(commentsList);

                PdfPTable storesTable = new PdfPTable(new float[] { 2f, 4f, 15f, 6f, 6f });
                storesTable.WidthPercentage = 65;
                storesTable.HeaderRows = 6;
                storesTable.FooterRows = 4;
                storesTable.SpacingBefore = 10f;
                emptyTableCell.Colspan = 5;

                storesTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                storesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                storesTable.AddCell(emptyTableCell);
                storesTable.AddCell(new Phrase("#", font10boldWhite));
                storesTable.AddCell(new Phrase("Site #", font10boldWhite));
                storesTable.AddCell(new Phrase("Site", font10boldWhite));
                storesTable.AddCell(new Phrase("Format", font10boldWhite));
                storesTable.AddCell(new Phrase("SEL", font10boldWhite));

                storesTable.AddCell(emptyTableCell);
                storesTable.AddCell(emptyTableCell);
                storesTable.AddCell(emptyTableCell);
                storesTable.AddCell(emptyTableCell);

                int cont = 1;
                string sameStoreName = null;
                foreach (var store in RangeReviewDomain.GetRangeReviewStores(rangeReview).Where(x => x.IsSelected))
                {
                    if (store.IsSameStore)
                    {
                        storesTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                        sameStoreName = store.Store.Name;
                    }
                    else
                    {
                        storesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }

                    storesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    storesTable.AddCell(new Phrase(cont++.ToString(), font10));
                    storesTable.AddCell(new Phrase(store.Store.Code, font10));
                    storesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    storesTable.AddCell(new Phrase(store.Store.Name, font10));
                    storesTable.AddCell(new Phrase(store.Store.Format, font10));
                    storesTable.AddCell(new Phrase(store.Store.SEL, font10));

                }

                document.Add(storesTable);

                commentsList = new List(List.UNORDERED, 20f);
                commentsList.SetListSymbol("\u2022");
                commentsList.IndentationLeft = 30f;
                commentsList.Add(new ListItem(string.Format("Same Store comparisons in each category report were calculated with data from {0} to {1}."
                                                                , rangeReview.FirstMonth.AddYears(-1).ToString("MMMM yyyy")
                                                                , rangeReview.FirstMonth.AddYears(-1).AddMonths(rangeReview.TotalMonths - 1).ToString("MMMM yyyy")), font14));
                if (sameStoreName != null)
                {
                    commentsList.Add(new ListItem(string.Format("{0} store was used to analyse sales-space performance.", sameStoreName.Trim()), font14));
                }

                document.Add(commentsList);

                #endregion

                #region Process and Methodology
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Process and Methodology";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                commentsList = new List(true, 30f);
                commentsList.IndentationLeft = 50f;
                commentsList.Add(new ListItem("Conversion and consolidation of sales information.", font16));
                commentsList.Add(new ListItem("Matching with Article Master for product description standardization and to eliminate de-listed products.", font16));
                commentsList.Add(new ListItem("Pareto on sales and Going-In Margin.", font16));
                commentsList.Add(new ListItem("Hurdle rates by categories / subcategories and SKUs.", font16));
                commentsList.Add(new ListItem("Match bottom 5% of Pareto and Hurdle rates below average.", font16));
                commentsList.Add(new ListItem("SKUs analysis versus sizes and flavours.", font16));
                commentsList.Add(new ListItem("Suggested final SKUs list for de-list.", font16));
                commentsList.Add(new ListItem("Market info analysis to identify gaps in range to suggest adding of products and categories performance review.", font16));
                commentsList.Add(new ListItem("Category comparison versus Previous year and Snack & Shop Same Store values.", font16));
                commentsList.Add(new ListItem("Subcategory comparison versus Previous year (Same Store values).", font16));
                commentsList.Add(new ListItem("Preliminary Category recommendation.", font16));
                commentsList.Add(new ListItem("Suggested final SKUs list for de-list.", font16));
                commentsList.Add(new ListItem("Deliver Executive Reports for main categories.", font16));

                document.Add(commentsList);

                #endregion

                #region Average Store, Concept & Calculation
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Average Store, Concept & Calculation";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                commentsList = new List(List.UNORDERED, 20f);
                commentsList.SetListSymbol("\u2022");
                commentsList.IndentationLeft = 50f;
                commentsList.Add(new ListItem("Concept", font16bold));

                document.Add(commentsList);
                document.Add(new Paragraph(" "));

                Paragraph para = new Paragraph("By Average Store we mean one that has ALL the recommended assortment for a store within the country, with their respective average sales and units.", font16);
                para.IndentationLeft = 50f;
                document.Add(para);

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                commentsList = new List(List.UNORDERED, 20f);
                commentsList.SetListSymbol("\u2022");
                commentsList.IndentationLeft = 50f;
                commentsList.Add(new ListItem("Calculation", font16bold));

                document.Add(commentsList);
                document.Add(new Paragraph(" "));

                commentsList = new List(true, 30f);
                commentsList.IndentationLeft = 50f;
                commentsList.Add(new ListItem("In preparation, select a sample of stores with a sales history (by SKU) of 6 and 12 months.", font16));
                commentsList.Add(new ListItem("Consolidate sales per SKU for the category/subcategory under review.", font16));
                commentsList.Add(new ListItem("This total per SKU, should then be divided by the number of months defined for the study to obtain an average sales value by SKU.", font16));
                commentsList.Add(new ListItem("Then, the resulting value should be divided by the number of stores in the sample, obtaining an average sales value by month and store.", font16));
                commentsList.Add(new ListItem("Adding all the average monthly sales per store of each SKU, we obtain the total normalized sales of the Category/Sub-Category under analysis.", font16));
                commentsList.Add(new ListItem("Following this scheme, when we add the normalized sales of all the categories we end up with a total that corresponds to the Average Store.", font16));

                document.Add(commentsList);

                #endregion

                #region Main Indicators Summary - Same Store
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Main Indicators Summary - Same Store";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable summaryTable = new PdfPTable(new float[] { 2f, 20f, 8f, 3f, 8f, 3f, 4f, 8f, 5f, 7f, 7f, 5f });
                summaryTable.WidthPercentage = 95;
                summaryTable.SpacingBefore = 20f;
                summaryTable.HeaderRows = 4;
                summaryTable.FooterRows = 2;
                emptyTableCell.Colspan = 12;

                summaryTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                summaryTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                summaryTable.DefaultCell.Rowspan = 2;
                summaryTable.AddCell(new Phrase("#", font10boldWhite));
                summaryTable.AddCell(new Phrase("Category", font10boldWhite));

                summaryTable.DefaultCell.Rowspan = 1;
                summaryTable.DefaultCell.Colspan = 2;
                summaryTable.AddCell(new Phrase("Sales", font10boldWhite));
                summaryTable.AddCell(new Phrase("GIM", font10boldWhite));

                summaryTable.DefaultCell.Rowspan = 2;
                summaryTable.DefaultCell.Colspan = 1;
                summaryTable.AddCell(new Phrase("GIM %", font10boldWhite));
                summaryTable.AddCell(new Phrase("Inventory " + currencySymbol, font10boldWhite));
                summaryTable.AddCell(new Phrase("Space (mt)", font10boldWhite));
                summaryTable.AddCell(new Phrase("Sales / Linear mt.", font10boldWhite));
                summaryTable.AddCell(new Phrase("GMROS (Monthly)", font10boldWhite));
                summaryTable.AddCell(new Phrase("SKUs with Sales", font10boldWhite));

                summaryTable.DefaultCell.Rowspan = 1;
                summaryTable.AddCell(new Phrase(currencySymbol, font10boldWhite));
                summaryTable.AddCell(new Phrase("%", font10boldWhite));
                summaryTable.AddCell(new Phrase(currencySymbol, font10boldWhite));
                summaryTable.AddCell(new Phrase("%", font10boldWhite));

                summaryTable.AddCell(emptyTableCell);
                summaryTable.AddCell(emptyTableCell);

                summaryTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                rank = 1;
                prevAcum = 0;
                acum = 0;
                foreach (var categoryItem in categorySalesSameStoreCY.OrderByDescending(x => x.GM))
                {
                    prevAcum = acum;
                    acum += categoryItem.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        summaryTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        summaryTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    summaryTable.AddCell(new Phrase(rank.ToString(), font10));

                    summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    summaryTable.AddCell(new Phrase(categoryItem.Category, font10));

                    summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    summaryTable.AddCell(new Phrase(categoryItem.Sales.ToString("C0"), font10));

                    summaryTable.AddCell(new Phrase((totalSaleSameStoreCY.Sales != 0 ? categoryItem.Sales / totalSaleSameStoreCY.Sales : 0).ToString("P1"), font10));

                    summaryTable.AddCell(new Phrase(categoryItem.GM.ToString("C0"), font10));

                    summaryTable.AddCell(new Phrase((totalSaleSameStoreCY.GM != 0 ? categoryItem.GM / totalSaleSameStoreCY.GM : 0).ToString("P1"), font10));

                    summaryTable.AddCell(new Phrase(categoryItem.GMPercent.ToString("P1"), font10));

                    summaryTable.AddCell(new Phrase(categoryItem.InventoryCost.ToString("C0"), font10));

                    summaryTable.AddCell(new Phrase(categoryItem.LinearSpace.ToString("N1") + " mt", font10));

                    summaryTable.AddCell(new Phrase(categoryItem.SalesOverLinearMt.ToString("C0"), font10));

                    summaryTable.AddCell(new Phrase(categoryItem.GMROS.ToString("C0"), font10));

                    var categoryAverageCY = categorySalesAverageStore.Where(x => x.CategoryId == categoryItem.CategoryId && !x.IsPriorYear).FirstOrDefault();

                    summaryTable.AddCell(new Phrase(categoryAverageCY != null ? categoryAverageCY.SKUs.ToString("N1") : string.Empty, font10));

                    rank++;
                }


                summaryTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                summaryTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                summaryTable.AddCell(" ");

                summaryTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                summaryTable.DefaultCell.Border = PdfPCell.BOX;

                summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                summaryTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                summaryTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.Sales.ToString("C0"), font10bold));
                summaryTable.AddCell(new Phrase("100%", font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.GM.ToString("C0"), font10bold));
                summaryTable.AddCell(new Phrase("100%", font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.GMPercent.ToString("P1"), font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.InventoryCost.ToString("C0"), font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.LinearSpace.ToString("N1") + " mt.", font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.SalesOverLinearMt.ToString("C0"), font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.GMROS.ToString("C0"), font10bold));
                summaryTable.AddCell(new Phrase(totalSaleSameStoreCY.SKUs.ToString("N0"), font10bold));




                document.Add(summaryTable);

                #endregion

                #region Assortment – Average Store
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment – Average Store";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                Dictionary<decimal, int> salesWithSkus = new Dictionary<decimal, int>();
                decimal prevAcumSales = 0;
                decimal acumSales = 0;
                int skusWithSales = 0;
                int skusInBottomFive = 0;
                decimal totalAverageSales = paretoItems.Where(x => !x.IsDeletedRangeReview).Sum(x => x.Sales);
                foreach (var sale in paretoItems.Where(x => !x.IsDeletedRangeReview))
                {
                    skusWithSales++;
                    prevAcumSales = acumSales;
                    acumSales += sale.Sales / totalAverageSales;

                    if (prevAcumSales < 0.1m && acumSales >= 0.1m)
                    {
                        salesWithSkus.Add(0.1m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.2m && acumSales >= 0.2m)
                    {
                        salesWithSkus.Add(0.2m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.3m && acumSales >= 0.3m)
                    {
                        salesWithSkus.Add(0.3m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.4m && acumSales >= 0.4m)
                    {
                        salesWithSkus.Add(0.4m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.5m && acumSales >= 0.5m)
                    {
                        salesWithSkus.Add(0.5m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.6m && acumSales >= 0.6m)
                    {
                        salesWithSkus.Add(0.6m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.7m && acumSales >= 0.7m)
                    {
                        salesWithSkus.Add(0.7m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.8m && acumSales >= 0.8m)
                    {
                        salesWithSkus.Add(0.8m, skusWithSales);
                    }
                    else if (prevAcumSales < 0.9m && acumSales >= 0.9m)
                    {
                        salesWithSkus.Add(0.9m, skusWithSales);
                    }

                    if (prevAcumSales >= 0.95m)
                        skusInBottomFive++;
                }

                salesWithSkus.Add(1m, skusWithSales);

                para = new Paragraph("SKUs", font14bold);
                para.IndentationLeft = 50f;
                document.Add(para);

                para = new Paragraph(string.Format("{0} SKUs in Article Master (Active)", skusWithSales), font14);
                para.IndentationLeft = 70f;
                document.Add(para);

                para = new Paragraph(string.Format("{0} SKUs make 80% of Sales", salesWithSkus[0.8m]), font14);
                para.IndentationLeft = 70f;
                document.Add(para);

                para = new Paragraph(string.Format("{0} SKUs in bottom 5% of Sales", skusInBottomFive), font14);
                para.IndentationLeft = 70f;
                document.Add(para);


                PdfPTable skusSalesTable = new PdfPTable(new float[] { 15f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f });
                skusSalesTable.WidthPercentage = 80;
                skusSalesTable.SpacingBefore = 20f;
                skusSalesTable.HeaderRows = 1;
                emptyTableCell.Colspan = 11;

                skusSalesTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                //header
                skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                skusSalesTable.AddCell(new Phrase("Total Store Sales", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("10%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("20%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("30%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("40%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("50%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("60%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("70%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("80%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("90%", font10boldWhite));
                skusSalesTable.AddCell(new Phrase("100%", font10boldWhite));

                //datos
                skusSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusSalesTable.AddCell(new Phrase("# SKUs", font10));
                skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                for (decimal index = 0.1m; index <= 1m; index += 0.1m)
                {
                    if (index == 0.8m)
                        skusSalesTable.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);
                    else
                        skusSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                    if (salesWithSkus.ContainsKey(index))
                    {
                        skusSalesTable.AddCell(new Phrase(salesWithSkus[index].ToString("N0"), font10));
                    }
                    else
                    {
                        skusSalesTable.AddCell(new Phrase("0", font10));
                    }
                }

                if (skusWithSales != 0)
                {
                    skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    skusSalesTable.AddCell(new Phrase("% SKUs", font10));
                    skusSalesTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    for (decimal index = 0.1m; index <= 1m; index += 0.1m)
                    {
                        if (index == 0.8m)
                            skusSalesTable.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);
                        else
                            skusSalesTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                        if (salesWithSkus.ContainsKey(index))
                        {
                            skusSalesTable.AddCell(new Phrase((salesWithSkus[index] / (decimal)skusWithSales).ToString("P1"), font10));
                        }
                        else
                        {
                            skusSalesTable.AddCell(new Phrase(0.ToString("P1"), font10));
                        }
                    }
                }

                document.Add(skusSalesTable);


                //Sales vs Skus
                RadChart salesVsSkusChart = ReportsHelper.GetLineChart("Pareto Sales", "SKUs", "Sales");
                salesVsSkusChart.Width = 610; //TODO: el width deberia de depender de si pongo comentarios a la izquierda o derecha del gráfico
                salesVsSkusChart.Height = 310; //TODO: el height debería de variar en base a si tengo info de inventarios, spaces, etc.     
                salesVsSkusChart.PlotArea.XAxis.MaxValue = 100;
                salesVsSkusChart.PlotArea.XAxis.MinValue = 0;
                salesVsSkusChart.PlotArea.XAxis.Step = 10;
                salesVsSkusChart.PlotArea.YAxis.MaxValue = 100;
                salesVsSkusChart.PlotArea.YAxis.MinValue = 0;
                salesVsSkusChart.PlotArea.YAxis.Step = 20;

                s1 = new ChartSeries("% SKUs");
                s1.Type = ChartSeriesType.Spline;
                s1.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                s1.Appearance.FillStyle.MainColor = barColors[0];

                if (skusWithSales != 0)
                {
                    for (decimal i = 0.1m; i <= 1m; i += 0.1m)
                    {
                        serieItem = new ChartSeriesItem();

                        if (salesWithSkus.ContainsKey(i))
                        {
                            serieItem.XValue = (double)(salesWithSkus[i] / (double)skusWithSales * 100);
                        }
                        else
                        {
                            serieItem.XValue = (double)0;
                        }

                        serieItem.YValue = (double)i * 100;
                        serieItem.Label.Visible = false;

                        s1.AddItem(serieItem);
                    }
                }

                salesVsSkusChart.Series.Add(s1);

                img = iTextSharp.text.Image.GetInstance(salesVsSkusChart.GetBitmap(), BaseColor.WHITE);
                img.Alignment = Image.ALIGN_CENTER;
                document.Add(img);


                #endregion

                #region # Skus – Average Store
                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "# Skus – Average Store";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                //TABLA IN OUT SKUS
                Font fontInOut = new Font(Calibri, 11f, Font.NORMAL, new BaseColor(80, 113, 154));

                PdfPTable inoutTable = new PdfPTable(new float[] { 10f, 5f, 5f, 5f, 5f });
                inoutTable.DefaultCell.Padding = 4f;
                inoutTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                inoutTable.DefaultCell.BorderColor = new BaseColor(80, 113, 154); //azul fuerte
                inoutTable.DefaultCell.BorderWidthTop = 0.5f;
                inoutTable.DefaultCell.BorderWidthBottom = 2f;
                emptyTableCell.Colspan = 5;

                inoutTable.DefaultCell.BorderWidthLeft = 0.5f;
                inoutTable.DefaultCell.BorderWidthRight = 0f;
                inoutTable.AddCell(new Phrase("DE-LIST PROPOSAL", fontInOut));
                inoutTable.DefaultCell.BorderWidthLeft = 0f;
                inoutTable.DefaultCell.BorderWidthRight = 0f;
                inoutTable.AddCell(new Phrase("# SKUs", fontInOut));
                inoutTable.AddCell(new Phrase("%", fontInOut));
                inoutTable.AddCell(new Phrase("SALES(*)", fontInOut));
                inoutTable.DefaultCell.BorderWidthRight = 1.5f;
                inoutTable.AddCell(new Phrase("%", fontInOut));
                inoutTable.AddCell(emptyTableCell);

                inoutTable.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241); //celeste
                inoutTable.DefaultCell.BorderWidthLeft = 0f;
                inoutTable.DefaultCell.BorderWidthRight = 0f;
                inoutTable.DefaultCell.BorderWidthTop = 0f;
                inoutTable.AddCell(new Phrase("IN", fontInOut));

                decimal inSkus = skusWithSales - totalDelistedSKUs;
                inoutTable.AddCell(new Phrase(inSkus.ToString("N0"), fontInOut));
                inoutTable.AddCell(new Phrase((inSkus / (decimal)skusWithSales).ToString("P1"), fontInOut));
                decimal inSkusSales = totalAverageSales - paretoItems.Where(x => x.Delist && !x.IsDeletedRangeReview).Sum(x => x.Sales);
                inoutTable.AddCell(new Phrase(inSkusSales.ToString("C0"), fontInOut));
                inoutTable.AddCell(new Phrase((inSkusSales / totalAverageSales).ToString("P1"), fontInOut));
                inoutTable.AddCell(emptyTableCell);

                inoutTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215); //azul
                inoutTable.AddCell(new Phrase("OUT", fontInOut));
                inoutTable.AddCell(new Phrase(totalDelistedSKUs.ToString("N0"), fontInOut));
                inoutTable.AddCell(new Phrase((totalDelistedSKUs / (decimal)skusWithSales).ToString("P1"), fontInOut));
                inoutTable.AddCell(new Phrase(paretoItems.Where(x => x.Delist && !x.IsDeletedRangeReview).Sum(x => x.Sales).ToString("C0"), fontInOut));
                inoutTable.AddCell(new Phrase((paretoItems.Where(x => x.Delist && !x.IsDeletedRangeReview).Sum(x => x.Sales) / totalAverageSales).ToString("P1"), fontInOut));
                inoutTable.AddCell(emptyTableCell);

                inoutTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                inoutTable.DefaultCell.BorderWidthLeft = 0.5f;
                inoutTable.DefaultCell.BorderWidthRight = 0f;
                inoutTable.DefaultCell.BorderWidthTop = 0.5f;
                inoutTable.AddCell(new Phrase("TOTAL ANALYZED", fontInOut));
                inoutTable.DefaultCell.BorderWidthLeft = 0f;
                inoutTable.DefaultCell.BorderWidthRight = 0f;
                inoutTable.AddCell(new Phrase(skusWithSales.ToString("N0"), fontInOut));
                inoutTable.AddCell(new Phrase("100 %", fontInOut));
                inoutTable.AddCell(new Phrase(totalAverageSales.ToString("C0"), fontInOut));
                inoutTable.DefaultCell.BorderWidthRight = 1.5f;
                inoutTable.AddCell(new Phrase("100 %", fontInOut));
                inoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                inoutTable.DefaultCell.Colspan = 5;
                inoutTable.AddCell(new Phrase("(*) Sales: Only active SKUs", fontInOut));


                //TABLA 
                PdfPTable skusTable = new PdfPTable(new float[] { 2f, 12f, 4f, 4f, 4f });
                skusTable.HeaderRows = 1;
                skusTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189);
                skusTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                skusTable.DefaultCell.Rowspan = 2;
                skusTable.AddCell(new Phrase("#", font10boldWhite));
                skusTable.AddCell(new Phrase("Category", font10boldWhite));
                skusTable.AddCell(new Phrase("AM Total SKUs", font10boldWhite));
                skusTable.AddCell(new Phrase("De-list Proposal", font10boldWhite));
                skusTable.AddCell(new Phrase("After RR", font10boldWhite));

                skusTable.DefaultCell.BackgroundColor = new BaseColor(194, 214, 153);
                skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                rank = 1;
                prevAcum = 0;
                acum = 0;
                foreach (var categoryItem in categorySalesSameStoreCY.OrderByDescending(x => x.GM))
                {
                    prevAcum = acum;
                    acum += categoryItem.GMShare;

                    if (prevAcum >= 0.8m && prevAcum < 0.95m)
                    {
                        skusTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    }
                    else if (prevAcum >= 0.95m)
                    {
                        skusTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                    }

                    skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    skusTable.AddCell(new Phrase(rank.ToString(), font10));
                    skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    skusTable.AddCell(new Phrase(categoryItem.Category, font10));
                    skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    int amTotalSKUs = paretoItems.Where(x => x.Category == categoryItem.Category && (!x.IsDeletedRangeReview || x.IsNew)).Count();
                    int delistProposal = paretoItems.Where(x => x.Category == categoryItem.Category && x.Delist && !x.IsDeletedRangeReview).Count();
                    skusTable.AddCell(new Phrase(amTotalSKUs.ToString("N0"), font10));
                    skusTable.AddCell(new Phrase(delistProposal.ToString("N0"), font10));
                    skusTable.AddCell(new Phrase((amTotalSKUs - delistProposal).ToString("N0"), font10));

                    rank++;
                }


                skusTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                skusTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                skusTable.AddCell(" ");

                skusTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216);
                skusTable.DefaultCell.Border = PdfPCell.BOX;

                int news = paretoItems.Where(x => x.IsNew).Count();
                int totalSkus = totalSaleAverageStoreCY.SKUs + news;

                skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusTable.AddCell(new Phrase("TOTAL STORE", font10bold));
                skusTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                skusTable.AddCell(new Phrase(totalSkus.ToString("N0"), font10bold));
                skusTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.SKUs.ToString("N0"), font10bold));
                skusTable.AddCell(new Phrase((totalSkus - totalSalesAverageStoreDelistCY.SKUs).ToString("N0"), font10bold));


                //LISTA DETALLE SKUS
                PdfPTable skusDetailsTable = new PdfPTable(new float[] { 65f, 35f });
                skusDetailsTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                emptyTableCell.Colspan = 2;

                Font fontUnderLined = new Font(Calibri, 11f, Font.UNDERLINE, BaseColor.BLACK);
                skusDetailsTable.DefaultCell.Colspan = 2;
                skusDetailsTable.AddCell(new Phrase("TOTAL STORE #SKUs:", fontUnderLined));

                skusDetailsTable.AddCell(emptyTableCell);

                skusDetailsTable.DefaultCell.Colspan = 1;
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("- Sales files: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                skusDetailsTable.AddCell(new Phrase(totalSaleSameStoreCY.SKUs.ToString("N0") + " SKUs", font12));

                skusDetailsTable.AddCell(emptyTableCell);

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("- Article Master: ", font12));
                skusDetailsTable.AddCell(" ");

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("   - With sales: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                skusDetailsTable.AddCell(new Phrase(totalSaleAverageStoreCY.SKUs.ToString("N0") + " SKUs (*)", font12));

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("   - New: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                
                skusDetailsTable.AddCell(new Phrase(news.ToString("N0") + " SKUs", font12));

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("   - TOTAL: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                
                skusDetailsTable.AddCell(new Phrase(totalSkus.ToString("N0") + " SKUs", font12));

                skusDetailsTable.DefaultCell.Colspan = 2;
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell("    (*) Analyzed in Range Review");

                skusDetailsTable.AddCell(emptyTableCell);

                skusDetailsTable.DefaultCell.Colspan = 1;
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("- Tryada Proposal: ", font12));
                skusDetailsTable.AddCell(" ");

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("   - De-list: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                skusDetailsTable.AddCell(new Phrase(totalSalesAverageStoreDelistCY.SKUs.ToString("N0") + " SKUs", font12));

                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                skusDetailsTable.AddCell(new Phrase("   - Total AM after RR: ", font12));
                skusDetailsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                skusDetailsTable.AddCell(new Phrase((totalSkus - totalSalesAverageStoreDelistCY.SKUs).ToString("N0") + " SKUs", font12));

                //LAYOUT
                layoutTable = new PdfPTable(2);
                layoutTable.SpacingBefore = 10f;
                layoutTable.WidthPercentage = 100;
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.DefaultCell.Padding = 10;

                layoutTable.AddCell(inoutTable);
                layoutTable.DefaultCell.Rowspan = 2;
                layoutTable.AddCell(skusTable);
                layoutTable.DefaultCell.Rowspan = 1;
                layoutTable.AddCell(skusDetailsTable);


                document.Add(layoutTable);

                #endregion

                #region Assortment Dynamic CY vs PY - Category Comparison Table

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                var salesByDateRows = ReportsRepository.GetSalesCategoryComparisonByDate(rangeReview.Id, null, 2);

                PdfPTable dynamicsTable = new PdfPTable(new float[] { 2f, 20f, 6f, 6f, 6f, 6f, 6f, 6f, 6f, 6f, 6f, 6f, 6f, });
                dynamicsTable.WidthPercentage = 95;
                dynamicsTable.HeaderRows = 5;
                dynamicsTable.FooterRows = 2;
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(191, 191, 191); //gris header y footer

                emptyTableCell.Colspan = 13;
                dynamicsTable.AddCell(emptyTableCell);

                emptyTableCell.Colspan = 2;
                dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                dynamicsTable.AddCell(emptyTableCell);
                dynamicsTable.DefaultCell.Colspan = 3;
                dynamicsTable.AddCell(new Phrase("# SKUS", font7));
                dynamicsTable.DefaultCell.Colspan = 2;
                dynamicsTable.AddCell(new Phrase("Current Year", font7));
                dynamicsTable.AddCell(new Phrase("Prior Year", font7));
                emptyTableCell.Colspan = 4;
                dynamicsTable.AddCell(emptyTableCell);


                dynamicsTable.DefaultCell.Colspan = 1;
                dynamicsTable.AddCell(new Phrase("#", font7));
                dynamicsTable.AddCell(new Phrase("Category", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153); //amarillo header
                dynamicsTable.AddCell(new Phrase("Active CY-PY", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(152, 255, 102); //verde header
                dynamicsTable.AddCell(new Phrase("New", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(255, 204, 0); //naranja header
                dynamicsTable.AddCell(new Phrase("Delisted", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                dynamicsTable.AddCell(new Phrase("Active CY-PY", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(152, 255, 102); //verde header
                dynamicsTable.AddCell(new Phrase("New", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                dynamicsTable.AddCell(new Phrase("Active CY-PY", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(255, 204, 0); //naranja header
                dynamicsTable.AddCell(new Phrase("Delisted", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                dynamicsTable.AddCell(new Phrase("Diff. Active CY-PY", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215); //azul header
                dynamicsTable.AddCell(new Phrase("Diff. New vs Delisted", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(254, 255, 153);
                dynamicsTable.AddCell(new Phrase("Diff. Active CY-PY %", font7));
                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                dynamicsTable.AddCell(new Phrase("Diff. New vs Delisted %", font7));

                emptyTableCell.Colspan = 13;
                dynamicsTable.AddCell(emptyTableCell);
                dynamicsTable.AddCell(emptyTableCell);

                decimal coverage = rrStores.Count * rangeReview.TotalMonths;

                var salesBySkuType = from item in paretoItemsWithPYSS
                                     group item by new { item.Id, item.Code, item.Name, item.Category, item.CategoryId, item.Subcategory } into g
                                     select new
                                     {
                                         ArticleId = g.Key.Id,
                                         Code = g.Key.Code,
                                         Name = g.Key.Name,
                                         Category = g.Key.Category,
                                         CategoryId = g.Key.CategoryId,
                                         Subcategory = g.Key.Subcategory,
                                         Sales = g.Sum(x => x.Sales),
                                         SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                         SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                         Status = (g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0) ? SKUStatus.Active :
                                                   g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) == 0 ? SKUStatus.New :
                                                   g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) == 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0 ? SKUStatus.Delisted : SKUStatus.None
                                     };

                var salesByCategory = from item in salesBySkuType
                                      group item by new { item.Category, item.CategoryId, item.Status } into g
                                      select new
                                      {
                                          CategoryId = g.Key.CategoryId,
                                          Category = g.Key.Category,
                                          Status = g.Key.Status,
                                          Sales = g.Sum(x => x.Sales),
                                          SalesCY = g.Sum(x => x.SalesCY),
                                          SalesPY = g.Sum(x => x.SalesPY),
                                          Skus = g.Count()
                                      };


                rank = 1;
                decimal difference = 0;
                decimal diffPerc = 0;
                foreach (var item in salesByCategory.Select(x => x.Category).Distinct())
                {
                    if (rank % 2 == 0)
                        dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(242, 242, 242); //gris row
                    else
                        dynamicsTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    dynamicsTable.AddCell(new Phrase(rank++.ToString("N0"), font7));
                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    dynamicsTable.AddCell(new Phrase(item, font7));

                    dynamicsTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.Skus).ToString("N0"), font7));
                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.New).Sum(x => x.Skus).ToString("N0"), font7));
                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Delisted).Sum(x => x.Skus).ToString("N0"), font7));

                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesCY).ToString("C0"), font7));
                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.New).Sum(x => x.SalesCY).ToString("C0"), font7));

                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesPY).ToString("C0"), font7));
                    dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY).ToString("C0"), font7));

                    difference = salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesCY) - salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesPY);
                    dynamicsTable.AddCell(new Phrase(difference.ToString("C0"), font7));

                    difference = salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.New).Sum(x => x.SalesCY) - salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY);
                    dynamicsTable.AddCell(new Phrase(difference.ToString("C0"), font7));

                    diffPerc = salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesPY) != 0 ?
                        salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesCY) / salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Active).Sum(x => x.SalesPY) - 1 : 0;

                    dynamicsTable.AddCell(new Phrase(diffPerc.ToString("P0"), font7));

                    diffPerc = salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY) != 0 ?
                        salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.New).Sum(x => x.SalesCY) / salesByCategory.Where(x => x.Category == item && x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY) - 1 : 0;

                    dynamicsTable.AddCell(new Phrase(diffPerc.ToString("P0"), font7));

                }

                emptyTableCell.Colspan = 2;
                dynamicsTable.AddCell(emptyTableCell);

                dynamicsTable.DefaultCell.BackgroundColor = new BaseColor(191, 191, 191);

                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.Skus).ToString("N0"), font7));
                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.Skus).ToString("N0"), font7));
                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.Skus).ToString("N0"), font7));

                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesCY).ToString("C0"), font7));
                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.SalesCY).ToString("C0"), font7));

                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesPY).ToString("C0"), font7));
                dynamicsTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY).ToString("C0"), font7));

                difference = salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesCY) - salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesPY);
                dynamicsTable.AddCell(new Phrase(difference.ToString("C0"), font7));

                difference = salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.SalesCY) - salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY);
                dynamicsTable.AddCell(new Phrase(difference.ToString("C0"), font7));

                diffPerc = salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesPY) != 0 ?
                    salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesCY) / salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesPY) - 1 : 0;

                dynamicsTable.AddCell(new Phrase(diffPerc.ToString("P0"), font7));

                diffPerc = salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY) != 0 ?
                    salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.SalesCY) / salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY) - 1 : 0;

                dynamicsTable.AddCell(new Phrase(diffPerc.ToString("P0"), font7));

                document.Add(dynamicsTable);


                para = new Paragraph();
                para.IndentationLeft = 40f;
                para.Font = font10;
                para.Add("Active CY-PY: Articles with sales in the prior year and the current year.");
                document.Add(para);

                para = new Paragraph();
                para.IndentationLeft = 40f;
                para.Font = font10;
                para.Add("New: Articles with sales in the current year but without sales in the prior year.");
                document.Add(para);

                para = new Paragraph();
                para.IndentationLeft = 40f;
                para.Font = font10;
                para.Add("Delisted: Articles with sales in the prior year and without sales in the current year.");
                document.Add(para);




                #endregion

                #region Assortment Dynamic CY vs PY - Total Monthly Sales

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                RadChart totalSalesChart = ReportsHelper.GetLineChart("Total Monthly Sales", null, null);
                totalSalesChart.Width = 750;
                totalSalesChart.Height = 350;
                totalSalesChart.PlotArea.YAxis.IsZeroBased = false;
                totalSalesChart.PlotArea.YAxis.Appearance.CustomFormat = "C0";
                totalSalesChart.PlotArea.XAxis.AutoScale = false;
                totalSalesChart.PlotArea.XAxis.IsZeroBased = false;
                totalSalesChart.PlotArea.XAxis.Appearance.ValueFormat = Telerik.Charting.Styles.ChartValueFormat.ShortDate;
                
                totalSalesChart.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.True;
                //totalSalesChart.PlotArea.XAxis.Appearance.LabelAppearance.RotationAngle = -45;
                //totalSalesChart.PlotArea.XAxis.Appearance.LabelAppearance.Position.AlignedPosition = Telerik.Charting.Styles.AlignedPositions.Top;
                totalSalesChart.PlotArea.XAxis.Appearance.CustomFormat = "MMMYY";
                totalSalesChart.PlotArea.YAxis.Appearance.MinorGridLines.Visible = true;
                totalSalesChart.PlotArea.XAxis.Appearance.MajorGridLines.Visible = true;


                var activeSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.Active)
                                 join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                                 select new { Date = sbd.Date, Sales = sbd.Sales };

                var newSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.New)
                              join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                              select new { Date = sbd.Date, Sales = sbd.Sales };

                var delistedSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.Delisted)
                                   join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                                   select new { Date = sbd.Date, Sales = sbd.Sales };

                var salesByDate = from item in salesByDateRows.Where(x => x.Date != DateTime.MinValue)
                                  group item by new { item.Date } into g
                                  select new
                                  {
                                      Date = g.Key.Date,
                                      TotalSales = g.Sum(x => x.Sales),
                                      ActiveSales = activeSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales),
                                      NewSales = newSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales),
                                      DelistedSales = delistedSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales)
                                  };

                DateTime stDt = rangeReview.HasPriorYear ? rangeReview.FirstMonth.AddMonths(-12) : rangeReview.FirstMonth;
                DateTime endDt = rangeReview.FirstMonth.AddMonths(rangeReview.TotalMonths);
                double startDate = new DateTime(stDt.Year, stDt.Month, 1).ToOADate();
                double endDate = new DateTime(endDt.Year, endDt.Month, 1).ToOADate();
                int totalMonths = rangeReview.HasPriorYear ? rangeReview.TotalMonths + 12 : rangeReview.TotalMonths;

                totalSalesChart.PlotArea.XAxis.AddRange(startDate, endDate, 31);

                ChartSeries serieActive = new ChartSeries(SKUStatus.Active.ToString());
                ChartSeries serieNew = new ChartSeries(SKUStatus.New.ToString());
                ChartSeries serieDelisted = new ChartSeries(SKUStatus.Delisted.ToString());
                ChartSeries serieTotal = new ChartSeries("Total Sales");

                serieActive.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                serieActive.Appearance.FillStyle.MainColor = barColors[0];
                serieActive.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                serieActive.Appearance.EmptyValue.Line.Width = 0;

                serieNew.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                serieNew.Appearance.FillStyle.MainColor = barColors[1];
                serieNew.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                serieNew.Appearance.EmptyValue.Line.Width = 0;

                serieDelisted.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                serieDelisted.Appearance.FillStyle.MainColor = barColors[2];
                serieDelisted.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                serieDelisted.Appearance.EmptyValue.Line.Width = 0;

                serieTotal.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                serieTotal.Appearance.FillStyle.MainColor = barColors[3];
                serieTotal.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                serieTotal.Appearance.EmptyValue.Line.Width = 0;


                serieActive.Type = ChartSeriesType.Line;
                serieNew.Type = ChartSeriesType.Line;
                serieDelisted.Type = ChartSeriesType.Line;
                serieTotal.Type = ChartSeriesType.Line;

                //foreach (var item in salesByDate.OrderBy(x => x.Date))
                for (int i = 0; i < totalMonths; i++)
                {
                    var item = salesByDate.Where(x => x.Date == stDt.AddMonths(i)).FirstOrDefault();
                    
                    if (item == null)
                    {
                        serieItem = new ChartSeriesItem(true);
                        serieActive.AddItem(serieItem);
                    }
                    else
                    {
                        serieItem = new ChartSeriesItem();
                        serieItem.Label.Visible = false;
                        serieItem.XValue = item.Date.ToOADate();
                        serieItem.YValue = (double)item.ActiveSales;
                        serieActive.AddItem(serieItem);
                    }

                    if (item == null)
                    {
                        serieItem = new ChartSeriesItem(true);
                        serieNew.AddItem(serieItem);
                    }
                    else
                    {
                        serieItem = new ChartSeriesItem();
                        serieItem.Label.Visible = false;
                        serieItem.XValue = item.Date.ToOADate();
                        serieItem.YValue = (double)item.NewSales;
                        serieNew.AddItem(serieItem);
                    }

                    if (item == null)
                    {
                        serieItem = new ChartSeriesItem(true);
                        serieDelisted.AddItem(serieItem);
                    }
                    else
                    {
                        serieItem = new ChartSeriesItem();
                        serieItem.Label.Visible = false;
                        serieItem.XValue = item.Date.ToOADate();
                        serieItem.YValue = (double)item.DelistedSales;
                        serieDelisted.AddItem(serieItem);
                    }

                    if (item == null)
                    {
                        serieItem = new ChartSeriesItem(true);
                        serieTotal.AddItem(serieItem);
                    }
                    else
                    {
                        serieItem = new ChartSeriesItem();
                        serieItem.Label.Visible = false;
                        serieItem.XValue = item.Date.ToOADate();
                        serieItem.YValue = (double)item.TotalSales;
                        serieTotal.AddItem(serieItem);
                    }
                }

                totalSalesChart.Series.Add(serieActive);
                totalSalesChart.Series.Add(serieNew);
                totalSalesChart.Series.Add(serieDelisted);
                totalSalesChart.Series.Add(serieTotal);

                img = iTextSharp.text.Image.GetInstance(totalSalesChart.GetBitmap(), BaseColor.WHITE);
                img.Alignment = Image.ALIGN_CENTER;
                document.Add(img);


                PdfPTable salesByTypeTable = new PdfPTable(new float[] { 15f, 10f, 10f, 10f });
                salesByTypeTable.WidthPercentage = 50;
                salesByTypeTable.SpacingBefore = 20f;
                salesByTypeTable.HorizontalAlignment = Element.ALIGN_LEFT;

                salesByTypeTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); // azul header
                salesByTypeTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                //header
                salesByTypeTable.AddCell(new Phrase("Status", font10boldWhite));
                salesByTypeTable.AddCell(new Phrase("# SKUs", font10boldWhite));
                salesByTypeTable.AddCell(new Phrase("PY Sales", font10boldWhite));
                salesByTypeTable.AddCell(new Phrase("CY Sales", font10boldWhite));

                salesByTypeTable.DefaultCell.BackgroundColor = BaseColor.WHITE;

                decimal totalCY, totalPY, aux = 0;
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                salesByTypeTable.AddCell(new Phrase("Active CY-PY", font10));
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                salesByTypeTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.Skus).ToString("N0"), font10));
                totalPY = salesByCategory.Sum(x => x.SalesPY) != 0 ? salesByCategory.Sum(x => x.SalesPY) : 0;
                aux = salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesPY);
                salesByTypeTable.AddCell(new Phrase((aux / totalPY).ToString("P2"), font10));
                totalCY = salesByCategory.Sum(x => x.SalesCY) != 0 ? salesByCategory.Sum(x => x.SalesCY) : 0;
                aux = salesByCategory.Where(x => x.Status == SKUStatus.Active).Sum(x => x.SalesCY);
                salesByTypeTable.AddCell(new Phrase((aux / totalCY).ToString("P2"), font10));

                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                salesByTypeTable.AddCell(new Phrase("New", font10));
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                salesByTypeTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.Skus).ToString("N0"), font10));
                aux = salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.SalesPY);
                salesByTypeTable.AddCell(new Phrase((aux / totalPY).ToString("P2"), font10));
                aux = salesByCategory.Where(x => x.Status == SKUStatus.New).Sum(x => x.SalesCY);
                salesByTypeTable.AddCell(new Phrase((aux / totalCY).ToString("P2"), font10));

                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                salesByTypeTable.AddCell(new Phrase("De-listed", font10));
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                salesByTypeTable.AddCell(new Phrase(salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.Skus).ToString("N0"), font10));
                aux = salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesPY);
                salesByTypeTable.AddCell(new Phrase((aux / totalPY).ToString("P2"), font10));
                aux = salesByCategory.Where(x => x.Status == SKUStatus.Delisted).Sum(x => x.SalesCY);
                salesByTypeTable.AddCell(new Phrase((aux / totalCY).ToString("P2"), font10));

                salesByTypeTable.DefaultCell.BorderColorTop = new BaseColor(79, 129, 189);
                salesByTypeTable.DefaultCell.BorderWidthTop = 1f;
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                salesByTypeTable.AddCell(new Phrase("Total General", font10bold));
                salesByTypeTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                salesByTypeTable.AddCell(new Phrase(salesByCategory.Sum(x => x.Skus).ToString("N0"), font10bold));
                salesByTypeTable.AddCell(new Phrase("100%", font10bold));
                salesByTypeTable.AddCell(new Phrase("100%", font10bold));

                layoutTable = new PdfPTable(2);
                layoutTable.DefaultCell.Border = PdfPCell.NO_BORDER;
                layoutTable.WidthPercentage = 100;

                layoutTable.DefaultCell.Padding = 15;
                layoutTable.AddCell(salesByTypeTable);
                layoutTable.AddCell(" ");

                document.Add(layoutTable);

                #endregion

                #region Assortment Dynamic CY vs PY - Total Monthly Sales - Zoom

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY - Zoom";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                totalSalesChart.Series.Remove(serieActive);
                totalSalesChart.Series.Remove(serieTotal);

                img = iTextSharp.text.Image.GetInstance(totalSalesChart.GetBitmap(), BaseColor.WHITE);
                img.Alignment = Image.ALIGN_CENTER;
                document.Add(img);

                #endregion

                #region Assortment Dynamic CY vs PY - Top 20 SKUs - Active PY-CY

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Top 20 SKUs - Active PY-CY";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                var salesTotalBySkuType = from item in salesByDateRows
                                          group item by new { item.Id, item.Code, item.Name, item.Category, item.Subcategory } into g
                                          select new
                                          {
                                              ArticleId = g.Key.Id,
                                              Code = g.Key.Code,
                                              Name = g.Key.Name,
                                              Category = g.Key.Category,
                                              Subcategory = g.Key.Subcategory,
                                              Sales = g.Sum(x => x.Sales),
                                              SalesCY = g.Where(x => !x.IsPriorYear).Sum(x => x.Sales),
                                              SalesPY = g.Where(x => x.IsPriorYear).Sum(x => x.Sales),
                                              Status = (g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0) ? SKUStatus.Active :
                                                        g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) > 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) == 0 ? SKUStatus.New :
                                                        g.Where(x => !x.IsPriorYear).Sum(x => x.Sales) == 0 && g.Where(x => x.IsPriorYear).Sum(x => x.Sales) > 0 ? SKUStatus.Delisted : SKUStatus.None
                                          };

                PdfPTable top20Table = new PdfPTable(new float[] { 8f, 15f, 15f, 6f });
                top20Table.WidthPercentage = 70;
                top20Table.SpacingBefore = 50f;

                top20Table.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header     
                top20Table.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                top20Table.AddCell(new Phrase("# Article", font10White));
                top20Table.AddCell(new Phrase("Article Name", font10White));
                top20Table.AddCell(new Phrase("Merchandise Category", font10White));
                top20Table.AddCell(new Phrase("Total", font10White));

                rank = 0;
                foreach (var item in salesTotalBySkuType.Where(x => x.Status == SKUStatus.Active).OrderByDescending(x => x.Sales))
                {
                    if (rank++ == 20)
                        break;

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    top20Table.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                    top20Table.AddCell(new Phrase(item.Code, font10White));

                    top20Table.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);
                    top20Table.AddCell(new Phrase(item.Name, font10));

                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Subcategory, font10));

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Sales.ToString("C0"), font10));
                }

                document.Add(top20Table);

                #endregion

                #region Assortment Dynamic CY vs PY - Top 20 SKUs - New

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Top 20 SKUs - New";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                top20Table = new PdfPTable(new float[] { 8f, 15f, 15f, 6f });
                top20Table.WidthPercentage = 70;
                top20Table.SpacingBefore = 50f;

                top20Table.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header      
                top20Table.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                top20Table.AddCell(new Phrase("# Article", font10White));
                top20Table.AddCell(new Phrase("Article Name", font10White));
                top20Table.AddCell(new Phrase("Merchandise Category", font10White));
                top20Table.AddCell(new Phrase("Total", font10White));

                rank = 0;
                foreach (var item in salesTotalBySkuType.Where(x => x.Status == SKUStatus.New).OrderByDescending(x => x.Sales))
                {
                    if (rank++ == 20)
                        break;

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    top20Table.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                    top20Table.AddCell(new Phrase(item.Code, font10White));

                    top20Table.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);
                    top20Table.AddCell(new Phrase(item.Name, font10));

                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Subcategory, font10));

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Sales.ToString("C0"), font10));
                }

                document.Add(top20Table);

                #endregion

                #region Assortment Dynamic CY vs PY - Top 20 SKUs - De-listed

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "Top 20 SKUs - De-listed";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                top20Table = new PdfPTable(new float[] { 8f, 15f, 15f, 6f });
                top20Table.WidthPercentage = 70;
                top20Table.SpacingBefore = 50f;

                top20Table.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header  
                top20Table.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                top20Table.AddCell(new Phrase("# Article", font10White));
                top20Table.AddCell(new Phrase("Article Name", font10White));
                top20Table.AddCell(new Phrase("Merchandise Category", font10White));
                top20Table.AddCell(new Phrase("Total", font10White));

                rank = 0;
                foreach (var item in salesTotalBySkuType.Where(x => x.Status == SKUStatus.Delisted).OrderByDescending(x => x.Sales))
                {
                    if (rank++ == 20)
                        break;

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    top20Table.DefaultCell.BackgroundColor = new BaseColor(149, 179, 215);
                    top20Table.AddCell(new Phrase(item.Code, font10White));

                    top20Table.DefaultCell.BackgroundColor = new BaseColor(219, 229, 241);
                    top20Table.AddCell(new Phrase(item.Name, font10));

                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Subcategory, font10));

                    top20Table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    top20Table.DefaultCell.BackgroundColor = BaseColor.WHITE;
                    top20Table.AddCell(new Phrase(item.Sales.ToString("C0"), font10));
                }

                document.Add(top20Table);

                #endregion


                #endregion

                #region Back Up - Final Recommendations

                #region Cover Page
                ((PageEvent)writer.PageEvent).Title = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Empty;
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = null;

                document.NewPage();

                caratula2 = new Paragraph();
                caratula2.SpacingBefore = 160f;
                caratula2.IndentationLeft = 100f;
                caratula2.IndentationRight = 20f;
                caratula2.MultipliedLeading = 2.5f;
                caratula2.Add(new Paragraph("Back Up - Final Recommendations", font30));
                document.Add(caratula2);

                document.Add(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLUE, 1, 0f)));
                #endregion

                #region Assortment Dynamic CY vs PY - Sales By Category


                var totalCategory = from item in salesByDateRows.Where(x => x.Date != DateTime.MinValue)
                                    group item by new { item.Category } into g
                                    select new
                                    {
                                        Category = g.Key.Category,
                                        TotalSales = g.Sum(x => x.Sales)
                                    };

                decimal total = totalCategory.Sum(x => x.TotalSales);

                prevAcum = 0;
                foreach (var cat in totalCategory.OrderByDescending(x => x.TotalSales))
                {
                    if (prevAcum >= 0.8m)
                        break;

                    activeSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.Active && x.Category == cat.Category)
                                 join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                                 select new { Date = sbd.Date, Sales = sbd.Sales };

                    newSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.New && x.Category == cat.Category)
                              join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                              select new { Date = sbd.Date, Sales = sbd.Sales };

                    delistedSKUs = from item in salesBySkuType.Where(x => x.Status == SKUStatus.Delisted && x.Category == cat.Category)
                                   join sbd in salesByDateRows on item.ArticleId equals sbd.Id
                                   select new { Date = sbd.Date, Sales = sbd.Sales };

                    salesByDate = from item in salesByDateRows.Where(x => x.Date != DateTime.MinValue && x.Category == cat.Category)
                                  group item by new { item.Date } into g
                                  select new
                                  {
                                      Date = g.Key.Date,
                                      TotalSales = g.Sum(x => x.Sales),
                                      ActiveSales = activeSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales),
                                      NewSales = newSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales),
                                      DelistedSales = delistedSKUs.Where(x => x.Date == g.Key.Date).Sum(x => x.Sales)
                                  };


                    prevAcum += salesByDate.Sum(x => x.TotalSales) / total;


                    ((PageEvent)writer.PageEvent).Title = "Back Up";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    RadChart totalCategorySalesChart = ReportsHelper.GetLineChart(cat.Category + " - Sales", null, null);
                    totalCategorySalesChart.Width = 750;
                    totalCategorySalesChart.Height = 350;
                    totalCategorySalesChart.PlotArea.YAxis.IsZeroBased = false;
                    totalCategorySalesChart.PlotArea.YAxis.Appearance.CustomFormat = "C0";
                    totalCategorySalesChart.PlotArea.XAxis.AutoScale = false;
                    totalCategorySalesChart.PlotArea.XAxis.IsZeroBased = false;
                    totalCategorySalesChart.PlotArea.XAxis.Appearance.TextAppearance.AutoTextWrap = Telerik.Charting.Styles.AutoTextWrap.True;
                    totalCategorySalesChart.PlotArea.XAxis.Appearance.ValueFormat = Telerik.Charting.Styles.ChartValueFormat.ShortDate;
                    totalCategorySalesChart.PlotArea.XAxis.Appearance.CustomFormat = "MMMYY";
                    totalCategorySalesChart.PlotArea.YAxis.Appearance.MinorGridLines.Visible = true;
                    totalCategorySalesChart.PlotArea.XAxis.Appearance.MajorGridLines.Visible = true;

                    //stDt = rangeReview.HasPriorYear ? rangeReview.FirstMonth.AddMonths(-rangeReview.TotalMonths) : rangeReview.FirstMonth;
                    //endDt = rangeReview.FirstMonth.AddMonths(rangeReview.TotalMonths);
                    //startDate = new DateTime(stDt.Year, stDt.Month, 1).ToOADate();
                    //endDate = new DateTime(endDt.Year, endDt.Month, 28).ToOADate();

                    totalCategorySalesChart.PlotArea.XAxis.AddRange(startDate, endDate, 31);

                    serieActive = new ChartSeries(SKUStatus.Active.ToString());
                    serieNew = new ChartSeries(SKUStatus.New.ToString());
                    serieDelisted = new ChartSeries(SKUStatus.Delisted.ToString());
                    serieTotal = new ChartSeries("Total Sales");

                    serieActive.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                    serieActive.Appearance.FillStyle.MainColor = barColors[0];
                    serieActive.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                    serieActive.Appearance.EmptyValue.Line.Width = 0;

                    serieNew.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                    serieNew.Appearance.FillStyle.MainColor = barColors[1];
                    serieNew.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                    serieNew.Appearance.EmptyValue.Line.Width = 0;

                    serieDelisted.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                    serieDelisted.Appearance.FillStyle.MainColor = barColors[2];
                    serieDelisted.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                    serieDelisted.Appearance.EmptyValue.Line.Width = 0;

                    serieTotal.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
                    serieTotal.Appearance.FillStyle.MainColor = barColors[3];
                    serieTotal.Appearance.EmptyValue.Mode = Telerik.Charting.Styles.EmtyValuesMode.Zero;
                    serieTotal.Appearance.EmptyValue.Line.Width = 0;

                    serieActive.Type = ChartSeriesType.Line;
                    serieNew.Type = ChartSeriesType.Line;
                    serieDelisted.Type = ChartSeriesType.Line;
                    serieTotal.Type = ChartSeriesType.Line;

                    for (int i = 0; i < totalMonths; i++)
                    {
                        var item = salesByDate.Where(x => x.Date == stDt.AddMonths(i)).FirstOrDefault();

                        if (item == null)
                        {
                            serieItem = new ChartSeriesItem(true);
                            serieActive.AddItem(serieItem);
                        }
                        else
                        {
                            serieItem = new ChartSeriesItem();
                            serieItem.Label.Visible = false;
                            serieItem.XValue = item.Date.ToOADate();
                            serieItem.YValue = (double)item.ActiveSales;
                            serieActive.AddItem(serieItem);
                        }

                        if (item == null)
                        {
                            serieItem = new ChartSeriesItem(true);
                            serieNew.AddItem(serieItem);
                        }
                        else
                        {
                            serieItem = new ChartSeriesItem();
                            serieItem.Label.Visible = false;
                            serieItem.XValue = item.Date.ToOADate();
                            serieItem.YValue = (double)item.NewSales;
                            serieNew.AddItem(serieItem);
                        }

                        if (item == null)
                        {
                            serieItem = new ChartSeriesItem(true);
                            serieDelisted.AddItem(serieItem);
                        }
                        else
                        {
                            serieItem = new ChartSeriesItem();
                            serieItem.Label.Visible = false;
                            serieItem.XValue = item.Date.ToOADate();
                            serieItem.YValue = (double)item.DelistedSales;
                            serieDelisted.AddItem(serieItem);
                        }

                        if (item == null)
                        {
                            serieItem = new ChartSeriesItem(true);
                            serieTotal.AddItem(serieItem);
                        }
                        else
                        {
                            serieItem = new ChartSeriesItem();
                            serieItem.Label.Visible = false;
                            serieItem.XValue = item.Date.ToOADate();
                            serieItem.YValue = (double)item.TotalSales;
                            serieTotal.AddItem(serieItem);
                        }
                    }

                    totalCategorySalesChart.Series.Add(serieActive);
                    totalCategorySalesChart.Series.Add(serieNew);
                    totalCategorySalesChart.Series.Add(serieDelisted);
                    totalCategorySalesChart.Series.Add(serieTotal);

                    img = iTextSharp.text.Image.GetInstance(totalCategorySalesChart.GetBitmap(), BaseColor.WHITE);
                    img.Alignment = Image.ALIGN_CENTER;
                    document.Add(img);

                    ((PageEvent)writer.PageEvent).Title = "Back Up";
                    ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Assortment Dynamic CY vs PY - Zoom";
                    ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                    document.NewPage();

                    totalCategorySalesChart.Series.Remove(serieActive);
                    totalCategorySalesChart.Series.Remove(serieTotal);

                    img = iTextSharp.text.Image.GetInstance(totalCategorySalesChart.GetBitmap(), BaseColor.WHITE);
                    img.Alignment = Image.ALIGN_CENTER;
                    document.Add(img);
                }

                #endregion

                #region De-listing Recommendations: SKUs and $ Sales: POG vs. Listing

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Format("De-listing Recommendations: SKUs and {0} Sales: POG vs. Listing", currencySymbol);
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable spaceDelistTable = new PdfPTable(new float[] { 2f, 18f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f });
                spaceDelistTable.WidthPercentage = 80;
                spaceDelistTable.SpacingBefore = 30f;

                spaceDelistTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header
                spaceDelistTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                spaceDelistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                spaceDelistTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                spaceDelistTable.DefaultCell.Rowspan = 2;
                spaceDelistTable.AddCell(new Phrase("#", font10White));
                spaceDelistTable.AddCell(new Phrase("Category", font10White));
                spaceDelistTable.DefaultCell.Rowspan = 1;
                spaceDelistTable.DefaultCell.Colspan = 2;
                spaceDelistTable.AddCell(new Phrase("POG", font10White));
                spaceDelistTable.AddCell(new Phrase("Listing", font10White));
                spaceDelistTable.AddCell(new Phrase("Unassigned Space", font10White));
                spaceDelistTable.AddCell(new Phrase("Total", font10White));
                spaceDelistTable.DefaultCell.Colspan = 1;
                spaceDelistTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistTable.AddCell(new Phrase("Sales", font10White));

                var delistingSkusAndSales = from item in salesBySpace.Where(x => x.Delist)
                                            group item by new { item.Category, item.PlanogramTypeName, item.PlanogramTypeId } into g
                                            select new { Category = g.Key.Category, PlanogramTypeName = g.Key.PlanogramTypeName, PlanogramTypeId = g.Key.PlanogramTypeId, Sales = g.Sum(x => x.Sales), SKUs = g.Count() };

                spaceDelistTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                spaceDelistTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                rank = 1;
                foreach (var categoryItem in categorySalesSameStoreCY.OrderByDescending(x => x.Sales))
                {
                    spaceDelistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceDelistTable.AddCell(new Phrase(rank++.ToString("N0"), font10));
                    spaceDelistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    spaceDelistTable.AddCell(new Phrase(categoryItem.Category, font10));

                    spaceDelistTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.Sales).ToString("C0"), font10));
                }

                emptyTableCell.Colspan = 1;
                spaceDelistTable.AddCell(emptyTableCell);
                spaceDelistTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216); //gris footer  
                spaceDelistTable.AddCell(" ");
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.Sales).ToString("C0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Sum(x => x.SKUs).ToString("N0"), font10));
                spaceDelistTable.AddCell(new Phrase(delistingSkusAndSales.Sum(x => x.Sales).ToString("C0"), font10));

                document.Add(spaceDelistTable);

                #endregion

                #region Skus and $ Sales: POG vs. Listing Total Store

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = string.Format("Skus and {0} Sales: POG vs. Listing Total Store", currencySymbol);
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable spaceTotalStoreTable = new PdfPTable(new float[] { 2f, 18f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f });
                spaceTotalStoreTable.WidthPercentage = 80;
                spaceTotalStoreTable.SpacingBefore = 30f;

                spaceTotalStoreTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header           
                spaceTotalStoreTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                spaceTotalStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                spaceTotalStoreTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                spaceTotalStoreTable.DefaultCell.Rowspan = 2;
                spaceTotalStoreTable.AddCell(new Phrase("#", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Category", font10White));
                spaceTotalStoreTable.DefaultCell.Rowspan = 1;
                spaceTotalStoreTable.DefaultCell.Colspan = 2;
                spaceTotalStoreTable.AddCell(new Phrase("POG", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Listing", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Unassigned Space", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Total", font10White));
                spaceTotalStoreTable.DefaultCell.Colspan = 1;
                spaceTotalStoreTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStoreTable.AddCell(new Phrase("Sales", font10White));

                var totalStoreSkusAndSales = from item in salesBySpace
                                             group item by new { item.Category, item.PlanogramTypeName, item.PlanogramTypeId } into g
                                             select new { Category = g.Key.Category, PlanogramTypeName = g.Key.PlanogramTypeName, PlanogramTypeId = g.Key.PlanogramTypeId, Sales = g.Sum(x => x.Sales), SKUs = g.Count() };

                spaceTotalStoreTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                spaceTotalStoreTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                rank = 1;
                foreach (var categoryItem in categorySalesSameStoreCY.Where(x => !x.IsPriorYear).OrderByDescending(x => x.Sales))
                {
                    spaceTotalStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceTotalStoreTable.AddCell(new Phrase(rank++.ToString("N0"), font10));
                    spaceTotalStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    spaceTotalStoreTable.AddCell(new Phrase(categoryItem.Category, font10));

                    spaceTotalStoreTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.Sales).ToString("C0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.SKUs).ToString("N0"), font10));
                    spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.Sales).ToString("C0"), font10));
                }

                emptyTableCell.Colspan = 1;
                spaceTotalStoreTable.AddCell(emptyTableCell);
                spaceTotalStoreTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216); //gris footer  
                spaceTotalStoreTable.AddCell(" ");
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales).ToString("C0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.SKUs).ToString("N0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.Sales).ToString("C0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Sum(x => x.SKUs).ToString("N0"), font10));
                spaceTotalStoreTable.AddCell(new Phrase(totalStoreSkusAndSales.Sum(x => x.Sales).ToString("C0"), font10));

                document.Add(spaceTotalStoreTable);

                #endregion

                #region De-listing Recommendations% Skus and % Sales: POG vs. Listing Total Store Share

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "De-listing Recommendations";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "% Skus and % Sales: POG vs. Listing Total Store Share";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable spaceDelistPercTable = new PdfPTable(new float[] { 2f, 18f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f });
                spaceDelistPercTable.WidthPercentage = 80;
                spaceDelistPercTable.SpacingBefore = 30f;

                spaceDelistPercTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header                
                spaceDelistPercTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                spaceDelistPercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                spaceDelistPercTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                spaceDelistPercTable.DefaultCell.Rowspan = 2;
                spaceDelistPercTable.AddCell(new Phrase("#", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Category", font10White));
                spaceDelistPercTable.DefaultCell.Rowspan = 1;
                spaceDelistPercTable.DefaultCell.Colspan = 2;
                spaceDelistPercTable.AddCell(new Phrase("POG", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Listing", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Unassigned Space", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Total", font10White));
                spaceDelistPercTable.DefaultCell.Colspan = 1;
                spaceDelistPercTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistPercTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistPercTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Sales", font10White));
                spaceDelistPercTable.AddCell(new Phrase("SKUs", font10White));
                spaceDelistPercTable.AddCell(new Phrase("Sales", font10White));

                var delistingPercSkusAndSales = from item in salesBySpace.Where(x => x.Delist)
                                                group item by new { item.Category, item.PlanogramTypeName, item.PlanogramTypeId } into g
                                                select new { Category = g.Key.Category, PlanogramTypeName = g.Key.PlanogramTypeName, PlanogramTypeId = g.Key.PlanogramTypeId, Sales = g.Sum(x => x.Sales), SKUs = g.Count() };

                decimal totalSKUs = totalStoreSkusAndSales.Sum(x => x.SKUs);
                decimal totalSales = totalStoreSkusAndSales.Sum(x => x.Sales);
                spaceDelistPercTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                spaceDelistPercTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                rank = 1;
                foreach (var categoryItem in categorySalesSameStoreCY.Where(x => !x.IsPriorYear).OrderByDescending(x => x.Sales))
                {
                    spaceDelistPercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceDelistPercTable.AddCell(new Phrase(rank++.ToString("N0"), font10));
                    spaceDelistPercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    spaceDelistPercTable.AddCell(new Phrase(categoryItem.Category, font10));

                    spaceDelistPercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                }

                emptyTableCell.Colspan = 1;
                spaceDelistPercTable.AddCell(emptyTableCell);
                spaceDelistPercTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216); //gris footer  
                spaceDelistPercTable.AddCell(" ");
                spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSKUs != 0 ? (delistingPercSkusAndSales.Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceDelistPercTable.AddCell(new Phrase(totalSales != 0 ? (delistingPercSkusAndSales.Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));

                document.Add(spaceDelistPercTable);

                #endregion

                #region Total Store% Skus and % Sales: POG vs. Listing Total Store Share

                ((PageEvent)writer.PageEvent).Title = "Back Up";
                ((PageEvent)writer.PageEvent).SubTitleFirstLine = "Total Store";
                ((PageEvent)writer.PageEvent).SubTitleSecondLine = "% Skus and % Sales: POG vs. Listing Total Store Share";
                ((PageEvent)writer.PageEvent).RangeReview = rangeReview.Title;

                document.NewPage();

                PdfPTable spaceTotalStorePercTable = new PdfPTable(new float[] { 2f, 18f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f, 7.5f });
                spaceTotalStorePercTable.WidthPercentage = 80;
                spaceTotalStorePercTable.SpacingBefore = 30f;

                spaceTotalStorePercTable.DefaultCell.BackgroundColor = new BaseColor(79, 129, 189); //azul header                
                spaceTotalStorePercTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY;
                spaceTotalStorePercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                spaceTotalStorePercTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                spaceTotalStorePercTable.DefaultCell.Rowspan = 2;
                spaceTotalStorePercTable.AddCell(new Phrase("#", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Category", font10White));
                spaceTotalStorePercTable.DefaultCell.Rowspan = 1;
                spaceTotalStorePercTable.DefaultCell.Colspan = 2;
                spaceTotalStorePercTable.AddCell(new Phrase("POG", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Listing", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Unassigned Space", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Total", font10White));
                spaceTotalStorePercTable.DefaultCell.Colspan = 1;
                spaceTotalStorePercTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Sales", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("SKUs", font10White));
                spaceTotalStorePercTable.AddCell(new Phrase("Sales", font10White));

                var totalStorePercSkusAndSales = from item in salesBySpace
                                                 group item by new { item.Category, item.PlanogramTypeName, item.PlanogramTypeId } into g
                                                 select new { Category = g.Key.Category, PlanogramTypeName = g.Key.PlanogramTypeName, PlanogramTypeId = g.Key.PlanogramTypeId, Sales = g.Sum(x => x.Sales), SKUs = g.Count() };

                spaceTotalStorePercTable.DefaultCell.BackgroundColor = BaseColor.WHITE;
                spaceTotalStorePercTable.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_BASELINE;
                rank = 1;
                foreach (var categoryItem in categorySalesSameStoreCY.Where(x => !x.IsPriorYear).OrderByDescending(x => x.Sales))
                {
                    spaceTotalStorePercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceTotalStorePercTable.AddCell(new Phrase(rank++.ToString("N0"), font10));
                    spaceTotalStorePercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    spaceTotalStorePercTable.AddCell(new Phrase(categoryItem.Category, font10));

                    spaceTotalStorePercTable.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category && x.PlanogramTypeId == null).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                    spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.Category == categoryItem.Category).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                }

                emptyTableCell.Colspan = 1;
                spaceTotalStorePercTable.AddCell(emptyTableCell);
                spaceTotalStorePercTable.DefaultCell.BackgroundColor = new BaseColor(216, 216, 216); //gris footer  
                spaceTotalStorePercTable.AddCell(" ");
                spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.POG.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeName == PlanogramType.Listing.ToString()).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Where(x => x.PlanogramTypeId == null).Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSKUs != 0 ? (totalStorePercSkusAndSales.Sum(x => x.SKUs) / totalSKUs).ToString("P1") : string.Empty, font10));
                spaceTotalStorePercTable.AddCell(new Phrase(totalSales != 0 ? (totalStorePercSkusAndSales.Sum(x => x.Sales) / totalSales).ToString("P1") : string.Empty, font10));

                document.Add(spaceTotalStorePercTable);


                #endregion


                #endregion





                //Cierro el documento y devuelvo los bytes.
                document.Close();
                return stream.ToArray();
            }

            return null;
        }

        public static byte[] QuickTest(int rangeReviewId, int categoryId)
        {
            //RangeReview rangeReview = RangeReviewDomain.GetById(rangeReviewId, true);
            //Category category = CategoriesDomain.GetById(categoryId);

            //string fileName = @"C:\Test.pdf";
            Document document = new Document(PageSize.LETTER.Rotate(), 0, 0, 0, 0);

            // step 2
            MemoryStream stream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, stream);
            PageEvent pageEvent = new PageEvent();
            pageEvent.Category = "Packaged Beverages";
            pageEvent.RangeReview = "Range Review 1";
            writer.PageEvent = pageEvent;

            // step 3
            document.Open();

            document.NewPage();

            StyleSheet css = new StyleSheet();
            css.LoadStyle("p_CF26408A", "margin", "20px 96px 10px 0px");
            css.LoadStyle("p_CF26408A", "text-align", "left");
            css.LoadStyle("p_CF26408A", "text-indent", "0pt");
            css.LoadStyle("p_CF26408A", "padding", "0px 0px 0px 0px");
            css.LoadStyle("p_CF26408A", "background-color", "#D8D8D8");

            css.LoadStyle("s_B5DCF17A", "font-family", "Arial");
            css.LoadStyle("s_B5DCF17A", "font-style", "Normal");
            css.LoadStyle("s_B5DCF17A", "font-weight", "Normal");
            css.LoadStyle("s_B5DCF17A", "font-size", "16px");
            css.LoadStyle("s_B5DCF17A", "color", "#000000");
            css.LoadStyle("s_B5DCF17A", "background-color", "#CCCCCC");

            css.LoadStyle("s_9E05C387", "font-family", "Arial");
            css.LoadStyle("s_9E05C387", "font-style", "Italic");
            css.LoadStyle("s_9E05C387", "font-weight", "Normal");
            css.LoadStyle("s_9E05C387", "font-size", "26");
            css.LoadStyle("s_9E05C387", "color", "#396BA7");
            css.LoadStyle("s_9E05C387", "background-color", "#CCCCCC");


            css.LoadStyle("divClass", "background-color", "#396BA7");


            string html = @"<html xmlns=http://www.w3.org/1999/xhtml><body style=""background-color:Red""><span class=""divClass""><ul style=list-style-type:disc><li value=1 class=p_CF26408A><span class=s_B5DCF17A>The </span><span class=s_9E05C387>Ireland </span><span class=s_B5DCF17A>Product Range Review was run from May 2010 to April 2011, with a sample of 11 OtR stores</span></li></ul><ul style=list-style-type:disc><li value=1 class=p_CF26408A><span class=s_9E05C387>Same Store</span><span class=s_B5DCF17A> and Europe comparisons in each category report were calculated with data from May 2010 to April 2011 vs. May 2009 to April 2010.</span></li></ul><ul style=list-style-type:disc><li value=1 class=p_CF26408A><span class=s_B5DCF17A>Ninth Lock (OtR) store was used to analyze sales-space performance and floorplan recommendations.</span></li></ul><ul style=list-style-type:disc><li value=1 class=p_CF26408A><span class=s_B5DCF17A>Available Data</span></li><li value=2 class=p_CF26408A><span class=s_9E05C387>Average Store:</span><span class=s_B5DCF17A> From from May 2010 to April 2011. Source BI SAP: Sales &amp; Margins.</span></li><li value=3 class=p_CF26408A><span class=s_9E05C387>Same Store:</span><span class=s_B5DCF17A> From May 2010 to April 2011 vs. May 2009 to April 2010. Source BI SAP: Sales &amp; Margins.</span></li><li value=4 class=p_CF26408A><span class=s_B5DCF17A>Gondolas / Widths planograms (Ninth Lock store)</span></li><li value=5 class=p_CF26408A><span class=s_9E05C387>Article Master</span><span class=s_B5DCF17A> (May 2010) (Ninth Lock store)</span></li><li value=6 class=p_CF26408A><span class=s_9E05C387>Inventories:</span><span class=s_B5DCF17A> Same Store, from May 2010 to April 2011 vs. May 2009 to April 2010. Source: BI SAP: Stock Value by SKU.</span></li><li value=7 class=p_CF26408A><span class=s_9E05C387>PI Differences and Charge Off</span><span class=s_B5DCF17A> information: May 2010 to April 2011. Source: PI SAP: PI Diff &amp; Charge-Offs report.</span></li><li value=8 class=p_CF26408A><span class=s_B5DCF17A>Category Role definition</span></li></ul></span></body></html>";
            List<IElement> objects = HTMLWorker.ParseToList(new StringReader(html), css);
            foreach (IElement element in objects)
                document.Add(element);

            document.Close();

            return stream.ToArray();
        }

        public static List<SalesCategoryComparisonPareto> GetSalesCategoryComparisonPareto(int rangeReviewId, int categoryId)
        {
            var paretoRows = ReportsRepository.GetSalesCategoryComparisonPareto(rangeReviewId, categoryId, false, 0, 1).ToList();
            return paretoRows.ConvertAll<SalesCategoryComparisonPareto>(c => new SalesCategoryComparisonPareto(c));
        }

        private class PageEvent : PdfPageEventHelper
        {
            private Font titleFont = null;
            private Font subtitleFont = null;
            private Font subtitle2Font = null;
            private Font numberFont = null;

            public string Title { get; set; }
            public string SubTitleFirstLine { get; set; }
            public string SubTitleSecondLine { get; set; }
            public string Category { get; set; }
            public string RangeReview { get; set; }
            public List<GeneralComment> GeneralComments { get; set; }


            public PageEvent()
            {
                BaseFont Calibri = ReportsHelper.GetCalibriOrDefault();

                titleFont = new Font(Calibri, 26, Font.BOLD, new BaseColor(31, 73, 125));
                subtitleFont = new Font(Calibri, 17, Font.BOLD, new BaseColor(31, 73, 125));
                subtitle2Font = new Font(Calibri, 15, Font.BOLD, new BaseColor(31, 73, 125));
                numberFont = new Font(Calibri, 14, Font.BOLD, BaseColor.WHITE);
            }

            public override void OnStartPage(PdfWriter writer, Document document)
            {
                if (document.PageNumber != 1)
                {
                    GeneralComment comment = null;

                    if (GeneralComments != null && GeneralComments.Where(x => x.Page == document.PageNumber && x.Section == ARR.Entities.Section.CompletePage.ToString()).Any())
                    {
                        comment = GeneralComments.Single(x => x.Page == document.PageNumber);
                    }

                    //HEADER
                    PdfPTable headerTable = new PdfPTable(3); // 3 columns
                    headerTable.WidthPercentage = 100f;
                    headerTable.SetWidths(new float[] { 10f, 70f, 20f });
                    headerTable.HorizontalAlignment = Element.ALIGN_LEFT;

                    PdfPCell headerCell1 = new PdfPCell();
                    headerCell1.BackgroundColor = new BaseColor(220, 227, 237);
                    headerCell1.Rowspan = 3;
                    headerCell1.BorderWidth = 0;
                    headerCell1.FixedHeight = 75f;
                    headerCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                    headerTable.AddCell(headerCell1);

                    string title = comment != null ? comment.PageTitle : this.Title;
                    PdfPCell headerCell2 = new PdfPCell(new Phrase(title != null ? title.ToUpper() : " ", titleFont));
                    headerCell2.BackgroundColor = new BaseColor(144, 168, 198);
                    headerCell2.Padding = 4f;
                    headerCell2.Border = Rectangle.NO_BORDER;
                    headerCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                    headerTable.AddCell(headerCell2);

                    PdfPCell headerCell3 = new PdfPCell(new Phrase(writer.PageNumber.ToString(), numberFont));
                    headerCell3.BackgroundColor = new BaseColor(157, 179, 205);
                    headerCell3.BorderWidth = 0;
                    headerCell3.Rowspan = 3;
                    headerCell3.Padding = 15;
                    headerCell3.VerticalAlignment = Element.ALIGN_BOTTOM;
                    headerCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                    headerTable.AddCell(headerCell3);

                    string subtitle1 = comment != null ? comment.PageSubtitle1 : this.SubTitleFirstLine;
                    PdfPCell headerCell22 = new PdfPCell(new Phrase(subtitle1 != null ? subtitle1.ToUpper() : " ", subtitleFont));
                    headerCell22.BackgroundColor = new BaseColor(144, 168, 198);
                    headerCell22.BorderWidth = 0;
                    headerCell22.VerticalAlignment = Element.ALIGN_MIDDLE;
                    headerCell22.Padding = 4f;
                    headerTable.AddCell(headerCell22);

                    string subtitle2 = comment != null ? comment.PageSubtitle2 : this.SubTitleSecondLine;
                    PdfPCell headerCell23 = new PdfPCell();
                    headerCell23.Phrase = new Phrase(subtitle2 != null ? subtitle2.ToUpper() : " ", subtitleFont);
                    headerCell23.BackgroundColor = new BaseColor(144, 168, 198);
                    headerCell23.BorderWidth = 0;
                    headerCell23.VerticalAlignment = Element.ALIGN_MIDDLE;
                    headerCell23.Padding = 4f;
                    headerTable.AddCell(headerCell23);


                    if (GeneralComments != null && GeneralComments.Where(x => x.Page == document.PageNumber && x.Section == ARR.Entities.Section.CompletePage.ToString()).Any())
                    {

                        byte[] pdf = GeneralComments.Single(x => x.Page == document.PageNumber).Pdf;

                        PdfContentByte cb = writer.DirectContent;
                        ColumnText ct = new ColumnText(cb);
                        ct.SetSimpleColumn(0, 612, 800, 75, 0, Element.ALIGN_LEFT);
                        ct.AddElement(headerTable);
                        ct.Go();

                        PdfPTable table = new PdfPTable(1);
                        table.WidthPercentage = 100;
                        table.DefaultCell.Border = PdfPCell.NO_BORDER;
                        PdfReader reader = new PdfReader(pdf);
                        int n = reader.NumberOfPages;
                        PdfImportedPage page;
                        for (int i = 1; i <= n; i++)
                        {
                            page = writer.GetImportedPage(reader, i);
                            Image pageImg = Image.GetInstance(page);
                            table.AddCell(pageImg);

                            PdfContentByte cb2 = writer.DirectContent;
                            ColumnText ct2 = new ColumnText(cb2);
                            ct2.SetSimpleColumn(0, 40, 800, 525, 0, Element.ALIGN_LEFT);
                            ct2.AddElement(table);
                            ct2.Go();
                        }

                        base.OnStartPage(writer, document);
                        document.NewPage();

                    }
                    else
                    {
                        document.Add(headerTable);
                        base.OnStartPage(writer, document);
                    }

                }


            }

            public override void OnEndPage(PdfWriter writer, Document document)
            {
                if (document.PageNumber != 1)
                {
                    //FOOTER
                    PdfPTable footerTable = new PdfPTable(new float[] { 20f, 5f, 45f, 30f }); // 3 columns
                    footerTable.WidthPercentage = 100f;
                    footerTable.HorizontalAlignment = Element.ALIGN_LEFT;

                    PdfPCell footerCell1 = new PdfPCell();
                    //footerCell1.BackgroundColor = new BaseColor(220, 227, 237);
                    footerCell1.BorderWidth = 0;
                    footerCell1.FixedHeight = 30f;
                    footerCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Images\logo_mini.png");
                    footerCell1.Image = iTextSharp.text.Image.GetInstance(path);
                    footerCell1.HorizontalAlignment = Element.ALIGN_CENTER;

                    PdfPCell footerCell2 = new PdfPCell();
                    footerCell2.BackgroundColor = new BaseColor(124, 153, 188);
                    footerCell2.BorderWidth = 0;

                    PdfPCell footerCell3 = new PdfPCell(new Phrase(this.Category != null ? this.Category : "Range Review Summary", subtitle2Font));
                    footerCell3.BackgroundColor = new BaseColor(144, 168, 198);
                    footerCell3.BorderWidth = 0;
                    footerCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
                    footerCell3.Padding = 4;


                    PdfPCell footerCell4 = new PdfPCell(new Phrase(this.RangeReview != null ? this.RangeReview.ToUpper() : this.RangeReview, subtitle2Font));
                    footerCell4.BackgroundColor = new BaseColor(144, 168, 198);
                    footerCell4.BorderWidth = 0;
                    footerCell4.VerticalAlignment = Element.ALIGN_MIDDLE;
                    footerCell4.HorizontalAlignment = Element.ALIGN_CENTER;

                    footerTable.AddCell(footerCell1);
                    footerTable.AddCell(footerCell2);
                    footerTable.AddCell(footerCell3);
                    footerTable.AddCell(footerCell4);

                    PdfContentByte cb = writer.DirectContent;
                    ColumnText ct = new ColumnText(cb);
                    ct.SetSimpleColumn(0, 0, 800, 30, 0, Element.ALIGN_LEFT);
                    ct.AddElement(footerTable);
                    ct.Go();

                    base.OnEndPage(writer, document);
                }
            }
        }

        private struct Recommendation
        {
            public int refNum { get; set; }

            public string Comment { get; set; }

            public Font lineFont { get; set; }
        }

        private class CYvsPY
        {
            public SalesCategoryComparison CY { get; set; }
            public SalesCategoryComparison PY { get; set; }
            public decimal SalesGrowth { get; set; }
            public decimal GMGrowth { get; set; }
            public decimal UnitsGrowth { get; set; }
            public decimal InventoryGrowth { get; set; }
            public decimal CYRank { get; set; }
            public decimal CYAcumGM { get; set; }
            public decimal CYPrevAcumGM { get; set; }
        }

        private class FillCell : IPdfPCellEvent
        {
            public float length;

            public FillCell(float length)
            {
                this.length = length;
            }

            public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas)
            {
                PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];
                cb.SaveState();

                cb.SetRGBColorFill(184, 205, 226);
                cb.Rectangle(rect.Left, rect.Bottom, rect.Width * length, rect.Height);
                cb.Fill();
                cb.RestoreState();
            }
        }

        public enum SKUStatus
        {
            Active,
            New,
            Delisted,
            None
        }

        public class StoreCoverageSegment
        {
            public string Segment { get; set; }
            public int ArticleId { get; set; }
            public short StoreId { get; set; }
            public decimal Sales { get; set; }
        }
    }
}
